Got a math calculation problem.
$a = 34.56 $b = 34.55
$a
do some calculation to get this figure
$b
is doing rounding to the nearest 0.05 to get this figure
what happens is
$c = $b - $a
supposedly it be -0.01, but I echo out the $c
, which shows -0.00988888888888
I try to use number_format($c, 2)
, but the output is 0.00,
how can I make sure $a
and $b
is exactly 2 decimals, no hidden number at the back.
in my php knowledge, number_format
is only able to format the display, but the value is not really 2 decimal,
I hope I can get help from here. This really frustrated me.
The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function.
$twoDecNum = sprintf('%0.2f', round($number, 2)); The rounding correctly rounds the number and the sprintf forces it to 2 decimal places if it happens to to be only 1 decimal place after rounding.
format("%. 2f", 1.23456); This will format the floating point number 1.23456 up-to 2 decimal places, because we have used two after decimal point in formatting instruction %.
Try sprintf
("%.2f", $c);
Floating point numbers are represented in IEEE notation based on the powers of 2, so terminating decimal numbers may not be a terminating binary number, that's why you get the trailing digits.
As suggested by Variable Length Coder, if you know the precision you want and it doesn't change (e.g. when you're dealing with money) it might be better to just use fixed point numbers i.e. express the numbers as cents rather than dollars
$a = 3456; $b = 3455; $c = $b - $a; sprintf ("%.2f", $c/100.0);
This way, you won't have any rounding errors if you do a lot of calculations before printing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With