开发者

PHP floor function

Does anyone know why floor(61681) = 61681, but floor(616.81*100) = 61680 ?

I have tried many others values like

floor(716.81*100) = 71681
floor(816.81*100) = 81681
floor(916.81*100) = 91681
floor(616.83*1开发者_C百科00) = 61683

Anyone know why this happened?


Because of the nature of binary floating-point numbers, internal rounding inaccuracies will occur. There is no way to represent 616.81 as a binary floating-point number exactly - its closest approximation is in fact slightly less than 616.81. 61681 can be represented exactly, however.

When the representation of 616.81 is multiplied by 100, the result is a tiny bit less than 61681, and thus calling floor on it will return 61680.

http://codepad.org/H0wh2itg

If you want absolute precision, you can use PHP's BC math functions, which can be as precise as you need at the cost of performance. For example:

var_dump(floor(bcmul(616.18, 100, 12)));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜