简体   繁体   English

PHP意外导致浮动到int类型转换

[英]PHP unexpected result of float to int type cast

I'trying to convert a float to an int value in php: 我想在php中将float转换为int值:

var_dump((int)(39.3 * 100.0)); //Returns 3929 but should be 3930!
var_dump((int)(39.2 * 100.0)); //Returns 3920

I can use ceil to make it work but can somebody explain this to me? 我可以使用ceil来使它工作,但是有人可以向我解释一下吗?

var_dump((int)ceil(39.3 * 100.0)); //Returns 3930

This is because numbers that have a finite representation in base 10 may or may not have an exact representation in the floating point representation PHP uses. 这是因为在基数10中具有有限表示的数字可能或可能不具有PHP使用的浮点表示中的精确表示。

See 看到

>php -r "echo var_dump(sprintf('%.40F', 39.3 * 100.0));"
string(45) "3929.9999999999995452526491135358810424804688"

Since int always rounds the number down, a small error in the representation makes the cast round it one number down that you would otherwise expect. 由于int总是将数字向下舍入,因此表示中的一个小错误会使得它会向下舍入一个你想要的数字。

Consider using round instead. 考虑使用round代替。

This might be late but the proper way to do it is as follows: 这可能会迟到,但正确的方法如下:

(int) bcmul(39.3, 100.0); // 3930
(int) bcmul(39.2, 100.0); // 3920

and for dealing with digits / calculation for floats, or anything that involves money transaction, you should never use directly multiplication/division + casting. 对于处理浮点数的数字/计算,或涉及金钱交易的任何事情,你不应该直接使用乘法/除法+铸造。

please refer to this as well: 请参考以下内容:

http://php.net/manual/en/book.bc.php http://php.net/manual/en/book.bc.php

notice: the casting in my answer is just to convert String to Int, (you don't need to do it) 注意:我的答案中的转换只是将String转换为Int,(你不需要这样做)

// gives: int(3930)
var_dump(intval((39.3 * 100.0) . '')); 

or, for use with a function: 或者,与功能一起使用:

function floatToInteger ($fValue)
{
    return (intval(($fValue + 0) . ''));
}

// gives: int(3930)
var_dump(floatToInteger(39.3 * 100.0));

You should have a look at this page: http://php.net/manual/en/language.types.float.php . 你应该看看这个页面: http//php.net/manual/en/language.types.float.php It describes the pitfalls working with floating point numbers. 它描述了使用浮点数的陷阱。

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

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