user2843198
user2843198

Reputation: 95

round() returns redundant amount of decimals

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

Answers (2)

user2191247
user2191247

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:

  • convert == with floating point to <= or >=
  • convert == to a tolerance, e.g. b–ε ≤ a ≤ b+ε, with ε some constant or value relative to |a| or |b| or both

Upvotes: 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.

  • Are you rounding a float? Use round
  • Are you wanting to format a number and group by thousands? Use number_format

<?php 
$number = '0.5600'; 
echo round((float)$number, 2, PHP_ROUND_HALF_DOWN);

https://eval.in/297781

Upvotes: 2

Related Questions