php function round
not working correctly.
I have number 0.9950
.
I put code:
$num = round("0.9950", 2);
And I get 1.0? Why?? Why I can't get 0.99
?
You can add a third parameter to the function to make it do what you need. You have to choose from one of the following :
This constants are easy enough to understand, so just use the adapted one :) In your example, to get 0.99, you'll need to use :
<?php echo round("0.9950", 2, PHP_ROUND_HALF_DOWN); ?>
When you round 0.9950
to two decimal places, you get 1.00
because this is how rounding works. If you want an operation which would result in 0.99
then perhaps you are looking for floating point truncation. One option to truncate a floating point number to two decimal places is to multiply by 100, cast to integer, then divide again by 100:
$num = "0.9950";
$output = (int)(100*$num) / 100;
echo $output;
0.99
This trick works because after the first step 0.9950
becomes 99.50
, which, when cast to integer becomes just 99
, discarding everything after the second decimal place in the original number. Then, we divide again by 100
to restore the original number, minus what we want truncated.
Just tested in PHP Sandbox... PHP seems funny sometimes.
<?php
$n = 16.90;
echo (100*$n)%100, "\n"; // 89
echo (int)(100*$n)%100, "\n"; // 89
echo 100*($n - (int)($n)), "\n"; // 90
echo (int)(100*($n - (int)($n))), "\n"; // 89
echo round(100*($n - (int)($n))), "\n"; // 90