简体   繁体   English

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

[英]PHP casting float to int returns different value

When I'm executing the following code in PHP (v5.5.9) something unexpected happens: 当我在PHP(v5.5.9)中执行以下代码时,会发生意外情况:

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

This returns 这回来了

float 54780
int 54779

So apparently the float value with no decimals, is not equal to the int value. 所以显然没有小数的浮点值不等于int值。 Any ideas of what's going on here? 关于这里发生了什么的任何想法?

When you divide $valueAsCents = 54780 / 100 then it becomes a float which is not always accurate in digital form because of the way they are stored. 当你将$ valueAsCents = 54780/100分开时,它就变成了一个浮点数,由于它们的存储方式,它在数字形式上并不总是准确的。 In my tests I got 在我的测试中,我得到了
547.7999999999999545252649113535881042480468750000 547.7999999999999545252649113535881042480468750000

When multiplied by 100 this is would be 当乘以100时,这将是
54779.9999999999927240423858165740966796870000 54779.9999999999927240423858165740966796870000

When PHP casts to int, it always rounds down. 当PHP转换为int时,它总是向下舍入。
When converting from float to integer, the number will be rounded towards zero. 从float转换为整数时,数字将向零舍入。

This is why the int value is 54779 这就是int值为54779的原因

Additionally, the PHP manual for float type also includes a hint that floating point numbers may not do what you expect. 此外, 浮动类型PHP手册还包括一个提示,浮点数可能无法达到您的预期。

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. 另外,可以精确表示为基数10中的浮点数的有理数,如0.1或0.7,不具有精确表示为基数2中的浮点数,其在内部使用,无论尾数的大小。 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.... 这可能导致令人困惑的结果:例如,floor((0.1 + 0.7)* 10)通常会返回7而不是预期的8,因为内部表示将类似于7.9999999999999991118 ....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM