开发者

How to deal with strange rounding of floats in PHP

As we all know, floating point arithmetic is not always completely accurate, but how do you deal with its inconsistencies?

As an example, in PHP 5.2.9: (this doesn't happen in 5.3)

echo round(14.99225, 4);  // 14.9923 
echo round(15.开发者_StackOverflow99225, 4);  // 15.9923 
echo round(16.99225, 4);  // 16.9922 ??
echo round(17.99225, 4);  // 17.9922 ??
echo round(25.99225, 4);  // 25.9922 ??
echo round(26.99225, 4);  // 26.9923

How would you work around this?


Welcome to IEEE754, enjoy your stay.

Use bc or gmp instead.


how do you deal with its inconsistencies?

  • For stuff where exact results based on decimal representation matters (i.e. money), do not use IEEE754 floats, you use "bignum" libraries like BCMath
  • For stuff where you just need your calculations to be relatively precise (like most scientific calculations), you use numerically stable algorithms so that the inconsistencies stay in the least significant bits (where they don't matter).
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜