gpt4 book ai didi

PHP 将 float 转换为 int 返回不同的值

转载 作者:可可西里 更新时间:2023-11-01 13:26:01 24 4
gpt4 key购买 nike

当我在 PHP (v5.5.9) 中执行以下代码时,发生了意外情况:

$valueAsCents = 54780 / 100 * 100;
var_dump($valueAsCents);
var_dump((int) $valueAsCents);

返回

float 54780
int 54779

很明显,没有小数点的浮点值不等于整数值。对这里发生的事情有什么想法吗?

最佳答案

当您除以 $valueAsCents = 54780/100 时,它变成一个 float ,由于它们的存储方式,它在数字形式中并不总是准确的。在我的测试中我得到了
547.7999999999999545252649113535881042480468750000

乘以 100 就是
54779.9999999999927240423858165740966796870000

当 PHP 转换为 int 时,它总是向下舍入。
When converting from float to integer, the number will be rounded towards zero.

这就是为什么int值是54779

另外,PHP manual for float type还包含一个提示,即 float 可能无法达到您的预期。

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they 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.9999999999999991118....

关于PHP 将 float 转换为 int 返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32589643/

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