Search code examples
phpfloating-pointdecimalrounding

php float calculation 2 decimal point


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.


Solution

  • 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.