Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 796
Shiro Avatar asked Oct 22 '09 02:10

Shiro


People also ask

How can I limit float to 2 decimal places in PHP?

The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function.

How can I get 2 decimal places in PHP?

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

How do you make a float to 2 decimal places?

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


1 Answers

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.

like image 179
Charles Ma Avatar answered Sep 20 '22 17:09

Charles Ma