Reputation: 95
I've written many PHP applications and have just stumbled upon a weird scenario. The round function doesn't seem to be working in a very complex set of code. I've tried many different things before calling round, but this just doesn't work. The function returns 0.56000000000000001 when given round($val,2)
, with $val=0.5600
. This should obviously return 0.56.
I've changed my code to use number_format($val,2,',','')
. This seems to have solved the issue, but now I'm 2nd guessing all my other code.
Should I replace round with number_format everywhere? Has anyone had similar errors with round?
Also to note this seems to be linked with PhpExcel which is used in this instance. https://github.com/PHPOffice/PHPExcel/issues/237
Upvotes: 0
Views: 423
Reputation:
The issue is that not every decimal number can be represented exactly in standard floating point. This is a very common problem, yours is not unique. If you need exact representation, then what you're doing, i.e. converting floating point to string, will suffice.
Some other solutions:
==
with floating point to <=
or >=
==
to a tolerance, e.g. b–ε ≤ a ≤ b+ε
, with ε
some constant or value relative to |a|
or |b|
or bothUpvotes: 0
Reputation: 11375
There is no need to replace round
with number_format
. You could use round
with the flag to round down.
Choose what is best for the application.
float
? Use round
number_format
<?php
$number = '0.5600';
echo round((float)$number, 2, PHP_ROUND_HALF_DOWN);
Upvotes: 2