在PHP中舍入 [英] Rounding in PHP

查看:134
本文介绍了在PHP中舍入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

($ 0.1 + 0.7)* 10)==(int)((0.1 + 0.7)* 10);(pre $ p)

PHP返回false。



解释我,为什么会发生?
首先返回8,第二个7。

解决方案

引用关于浮点精度PHP手册中的大红色警告


通常情况下,简单的小数点如 0.1 0.7 不能是转换成其内部的二进制对应,而不会有小的精度损失。这可能会导致令人困惑的结果:例如, floor((0.1 + 0.7)* 10)通常会返回 7 而不是所期望的 8 ,因为内部表示将类似于 7.9



这是由于这样的事实,即不可能用有限的数字来表示一些十进制符号的分数。例如,小数形式的 1/3 变成 0.3



所以不要相信浮点数结果到最后一个数字,也不要比较浮点数是否相等。如果需要更高的精确度,任意精度数学函数 gmp 功能可用。


$a = ((0.1 + 0.7) * 10) == (int)((0.1 + 0.7) * 10);

PHP returns false.

Could anybody explain me, why that happens? First returns 8, second 7.

解决方案

Quoting the big fat red warning in the PHP Manual on Floating Point Precision:

It is typical that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9.

This is due to the fact that it is impossible to express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3.

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

这篇关于在PHP中舍入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆