gpt4 book ai didi

php - 在 PHP 中舍入

转载 作者:可可西里 更新时间:2023-10-31 23:52:20 24 4
gpt4 key购买 nike

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

PHP 返回错误。

谁能解释一下,为什么会这样?第一个返回 8,第二个返回 7。

最佳答案

引用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 - 在 PHP 中舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3512663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com