How to deal with strange rounding of floats in PHP

断了今生、忘了曾经 提交于 2019-12-12 08:37:28

问题


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.99225, 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?


回答1:


Welcome to IEEE754, enjoy your stay.

Use bc or gmp instead.




回答2:


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


来源:https://stackoverflow.com/questions/2248835/how-to-deal-with-strange-rounding-of-floats-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!