Reputation: 1167
Possible Duplicate:
PHP: show a number to 2 decimal places
How do I cast an integer, let's say $i=50
to a float with two decimal values: $m=50.00
? I have tried (float)$i
but nothing happens.
EDIT:
I need to make $i == $m
so that returns TRUE
;
Upvotes: 3
Views: 51021
Reputation: 2708
round((float)$i, 2)
Should do the trick.
The round
function is built in and rounds a given float to the number of decimal places specified in the given argument.
Ahh yes, number_format($var, 2)
is good as well !
You can also find the recommended Answer of the PHP Collective in this Question which refers to this function page.
$foo = "105";
echo number_format((float)$foo, 2, '.', ''); // Outputs -> 105.00
Upvotes: 10
Reputation: 1055
If you're just using the regular equality operator (==
) instead of the type-safe equality operator (===
) you shouldn't have any problems.
Comparing a double to an int with the same values:
$i = 20;
$m = 20.00;
gettype($i); // integer
gettype($m); // double
$i == $m; // true;
$i === $m; // false, $m is a double and $i is an integer.
If we would like to fix that, however, we just need to do:
$i = (double)$i;
gettype($i); // double
$i === $m; // true!
Upvotes: 8
Reputation: 354774
For floating point numbers the number of decimal digits is a formatting property, that is the number itself doesn't know about those things. A float
50 is stored as an exact integer 50. You need to format the number (using sprintf
for example) to be written with decimal digits.
Upvotes: 7