php float calculation 2 decimal point

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.


Use round():

$c = round($b - $a, 2);

Note: you can also choose the rounding mode as appropriate.

Edit: Ok I don't get what sprintf() is doing that number_format() isn't:

$c = number_format($b - $a, 2);

vs

$c = sprintf("%.2f", $b - $a);

?