php float calculation 2 decimal point

Viewed 86533

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.

7 Answers

You can very neatly sidestep all of these issues simply by using the bcmath library.

Just remember to read the documentation and be careful whether you are passing arguments as strings or as numeric datatypes.

Related