Just a question about str_replace - php

I have a question about str_replace in PHP. When I do:
$latdir = $latrichting.$Lat;
If (preg_match("/N /", $latdir)) {
$Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
$Latcoorl = str_replace ("S ", "-",$latdir);
}
print_r($latdir);
print_r($Latcoorl);
print_r($latdir); gives :N52.2702777778
but print_r ($Latcoorl); gives :N52.270277777800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
Yes, it adds a lot of zeros. Can someone explane this behavior just for the fun of it?
print_r ($latrichting);
give's: N
print_r ($Lat);
This give's the weird long number.
So its probably not the str_replace command, you think ?

$latmin2 = bcdiv($latsec, 60, 20);
$latmin_total = $latmin + $latmin2;
$lat = bcdiv($latmin_total, 60, 20);
$latdir = array("N" => 1, "S" => -1);
$latcoorl = $latdir * $latdir[$latrichting];
Happy New Year.

Your string replace search string has a space before the 'N' while the dumped value looks like it's N:
Not sure what it has to do with all the zeros though.

On my system this code fragment:
<?php
$latdir = ':N52.2702777778';
If (preg_match("/N /", $latdir)) {
$Latcoorl = str_replace(" N ", "+",$latdir);
}
else {
$Latcoorl = str_replace ("S ", "-",$latdir);
}
print_r($latdir);
print_r($Latcoorl);
?>
gives the following result:
:N52.2702777778:N52.2702777778
My best guess is you have something after this code that prints out a serie of 0.

How I would do it; just a variation of Anthony's original answer that keeps everything as numeric and doesn't lapse into string mode.
$Latcoorl = ($latrichting == "N") ? ($Lat) : (-1 * $Lat);

The string operations you did won't generate any 0s.
The 0s have to come from $lat. What did you do with $lat? any division by pi? PHP will try to store the most accurate possible float number in $lat. That's not really a problem, its a correct behavior. Just truncate the number when displayed, or round it up.

Related

Force currency format regardless of input

Regardless of what format the input is in, I am trying to use PHP to modify it, so the output is always consistent, rounds to two decimal places and has a dollar sign. My approach does not yield desired results all the time, I was wondering if someone can help me come up with a more robust solution?
Desired output:
$num = "$12.00"; //output $12.00
$num = "125"; //output $125.00
$num = "$300"; //output $300.00
$num = "17.5"; //output $17.50
$num = "1,777.5"; //output $1777.50
What I tried, however this does not work for all cases:
$num = "$" . str_replace("$", "", round($num,0)) . ".00";
I appreciate any advice! Many thanks in advance!
$num = "$" . str_replace("$", "", round($num,0));
In this line you round before you remove the $-sign. I must be the other way round:
$num = "$" . round(str_replace("$", "", $num),0);
EDIT: And to get the output you want, you might want to use number_format() instead of round()
$num = "$" . number_format(str_replace("$", "", $num),2, '.', '');

Change from string to variable

Hi Guys , just need a tiny help here . the green numbers on the right are strings . how do I change them to numbers ? Additionally I also need them to be 2 decimal place. What function do I use?? I tried the method below but the output was 0. Answers all welcome.
$profitText = $profitText*1;
$profitText = (float)$profitText;
round($profitText,2);
number_format($profitText, 2);
EDITED
Okay guys the deriving of this variable is really complex. every step has its functional purpose but heres the derivation. After the last profitText at the bottom, I realised this is now a string. why is that so? and how do I fix it?
$offeropen=$row['offerprice'];//1.3334
$pips=$offerpricepl-$offeropen;//difference btw prices , eg. 0.0023
$closedb=$offerpricepl;// nothing
$pips1=round($pips, 6);// round to 6 decimal points
$pips2 = str_replace('.', '', $pips1);// remove decimal
if ($pips2<0)
{
$pips2 = str_replace('-', '', $pips2);// methodology for adjusting figures and negative values back
$pips2 = ltrim($pips2, '0');
$pips2 = -1 * abs($pips2);
}
else {
$pips2 = ltrim($pips2, '0');// for triming 0 on the left
}
$pips3=$pips2/$minipipskiller;// methodology
$ticksize= "0.0001";// FOR PROFIT AND LOSS
$lot1 = "100000";
$sizecalc=$row['size'] * $lot1;
if ($row['type']=="buy")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
if ($row['type']=="sell")
{
$profitandloss=$sizecalc*$ticksize*$pips3; //per TRADE
}
$zero= '0';
if($profitandloss<$zero) {
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
} elseif ($profitandloss>$zero) {
$profitText = "<div style=\"color: green;\">$profitandloss</div>";
}
// for profit and loss counting
$profitText=ltrim($profitText,'0');
Here's your problem:
$profitText = "<div style=\"color: red;\">$profitandloss</div>";
You're trying to turn $profitText into a number. It's actually a string of HTML, and PHP can't manage to work out what it's supposed to do with it, so when you cast it to a number, it's returning 0.
Solution:
Use $profitandloss instead
this will do both requested points together:
$floatProfitVar = number_format($profit, 2, '.');
I think you need
floatval(mixed var)
http://www.php.net/manual/en/function.floatval.php
$profit = round(floatval(trim($profitText)), 2);
Proof: http://codepad.org/jFTqhUIk
The function you're looking for is sprintf or printf and has been designed for exactly that job:
printf('%.2F', '1.8'); # prints "1.80"
Demo: https://eval.in/44078
You can use string input for the float number parameter (F = float, locale independent) as well as integer or float input. PHP is loosely typed.
Use sprintf if you want to get back a string, printf prints directly.
$value = intval(floatval($profitText)*100)/100.0
I don't think this $profitText = $profitText*1; would work unless you first do $profitText = (float)$profitText;. Remember that you have to convert the string first before you can do any manipulation.
floatval(mixed $var) can also be used instead of typecasting but typecasting should work fine

PHP increase number by one

This is a tricky one: I want to add +1 to this number: 012345675901 and the expected result is: 012345675902. Instead I get: 2739134 when I do this:
echo (012345675901+1);
When I try:
echo ('012345675901'+1);
I get this: 12345675902 which is pretty close to what I need, but it removes the leading zero.
When I do this:
echo (int) 012345675901;
I get 2739133. I also tried bcadd() without success:
echo bcadd(012345675901, 1);
which resulted in 2739134.
I know I am missing something here. I would really appreciate your help!
UPDATE 1
Answer 1 says that the number is octal:
function is_octal($x) {
return decoct(octdec($x)) == $x;
}
$number = is_octal(012345675901);
echo var_dump($number);
The above returns false. I thought I needed to convert this from octal to a normal string but didn't work. I can't avoid not using the above number - I just need to increment it by one.
EDIT 2
This is the correct code:
$str = '012345675901';
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros
Thank you everyone for your help! The above code produces: 012345675902 as expected
The leading 0 is treating your number as octal.
The leading 0 you need for output as a string, is a purely a representation.
please see the code for explanation.
$str = "012345675901"; // your number
$str1 = ltrim($str, '0'); // to remove the leading zero
$str2 = bcadd($str1, 1); // +1 to your result
$str3 = strlen($str); // get the length of your first number
echo str_pad($str2, $str3, '0', STR_PAD_LEFT); // apply zeros

function to return the numeric value

What would be an elegant way of doing this?
I have this -> "MC0001" This is the input. It always begins with "MC"
The output I'd be aiming with this input is "MC0002".
So I've created a function that's supposed to return "1" after removing "MC000". I'm going to convert this into an integer later on so I could generate "MC0002" which could go up to "MC9999". To do that, I figured I'd need to loop through the string and count the zeros and so on but I think I'd be making a mess that way.
Anybody has a better idea?
This should do the trick:
<?php
$string = 'MC0001';
// extract the part succeeding 'MC':
$number_part = substr($string, 2);
// count the digits for later:
$number_digits = strlen($number_part);
// turn it into a number:
$number = (int) $number_part;
// make the next sequence:
$next = 'MC' . str_pad($number + 1, $number_digits, '0', STR_PAD_LEFT);
using filter_var might be the best solution.
echo filter_var("MC0001", FILTER_SANITIZE_NUMBER_INT)."\n";
echo filter_var("MC9999", FILTER_SANITIZE_NUMBER_INT);
will give you
0001
9999
These can be cast to int or just used as they are, as PHP will auto-convert anyway if you use them as numbers.
just use ltrim to remove any leading chars: http://php.net/manual/en/function.trim.php
$str = ltrim($str, 'MC0');
$num = intval($str);
<php
// original number to integer
sscanf( $your_string, 'MC%d', $your_number );
// pad increment to string later on
sprintf( 'MC%04u', $your_number + 1 );
Not sure if there is a better way of parsing a string as an integer when there are leading zero's.
I'd suggest doing the following:
1. Loop through the string ( beginning at location 2 since you don't need the MC part )
2. If you find a number thats bigger than 0, stop, get the substring using your current location and the length of the string minus your current location. Cast to integer, return value.
You can remove the "MC" par by doing a substring operating on the string.
$a = "MC0001";
$a = substr($a, 2); //Lengths of "MC"
$number = intval($a); //1
return intval(str_replace($input, 'MC', ''), 10);

PHP: Max and Min returning incorrect results

I am sure this is because of the "g" on the end but this is the scenario and results when I try and work out a ratio percent. I always want to divide the highest of 2 numbers by the lowest.
$item1 = "200.00g";
$item2 = "50.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "400%"
$item1 = "100.00g";
$item2 = "5.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "2000%"
PROBLEM RESULT:
$item1 = "8.00g";
$item2 = "14.00g";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
// result: $calc = "57%"
// I am expecting (14.00g / 8.00g)*100 = "175%"
It's type casting;
$item1 = "8.00";
$item2 = "14.00";
$calc = round((max($item1,$item2) / min($item1,$item2))*100) . "%";
result will be 175%
When you want to use your strings in mathematical operations, and you know that the unit is placed at the end as it is in your example, you can cast your variables to floats:
$item1_numeric = (float) $item1;
But obviously it is better to have the values and the units separated in your variables / database.
Use: substr($item1, 0, -1) instade of $item1, substr($item2, 0, -1) instade of $item2 when you do round.
You can't compare 2 strings with round().
Edit : If $item1 = "200g", ma solution is ok, but if if $item1 = "200.00g" you need to remove "." before round() with for example pregreplace.
Oh, YAPHPB - and one of my favorite ones. Even though it's written in the Doc:
When [max()] given a string it will be cast as an integer when comparing.
... it's only a partial truth: if at least one of compared values is a number, or a numeric string.
Otherwise all the strings will be compared as strings: first {0} characters of each strings will be compared, then {1}, then {2}... etc.
So basically that's what happens here:
echo max("200.00g", "50.00g"); // 50.00g, as '5' > '2'
echo max("200.00g", 50); // "200.00g", as it gets converted to int (become 200)
And that's even more crazy:
echo max("200.00g", "1000.00"); // "200.00g", as '2' > '1'
echo max("200.00", "1000.00"); // "1000.00", as we tried to help you, no, really!
The latter result can actually be predicted by someone knowing of numeric concept: when both strings are pure numbers, they got converted to numbers when compared. Still, I found this behavior unreliable, to say the least.
The bottom line: if you need to compare numbers, compare numbers, period. Type conversion in PHP can get real messy - and bite you in the bottom real hard when you least expect it. )

Categories