PHP意外的结果float到int类型转换 [英] PHP unexpected result of float to int type cast
本文介绍了PHP意外的结果float到int类型转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图将一个float转换为一个int值在php:
I'trying to convert a float to an int value in php:
var_dump((int)(39.3 * 100.0)); //Returns 3929 but should be 3930!
var_dump((int)(39.2 * 100.0)); //Returns 3920
我可以使用ceil使其工作,但是有人可以向我解释这个吗? / p>
I can use ceil to make it work but can somebody explain this to me?
var_dump((int)ceil(39.3 * 100.0)); //Returns 3930
推荐答案
在基础10中的有限表示可以或可以不具有在PHP使用的浮点表示中的精确表示。
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.
请参阅
>php -r "echo var_dump(sprintf('%.40F', 39.3 * 100.0));"
string(45) "3929.9999999999995452526491135358810424804688"
由于 int
考虑使用 round
。
这篇关于PHP意外的结果float到int类型转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文