本文介绍了浮点到 int 类型转换的 PHP 意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!
问题描述
我试图在 php 中将浮点数转换为 int 值:
var_dump((int)(39.3 * 100.0));//返回3929但应该是3930!var_dump((int)(39.2 * 100.0));//返回3920
我可以使用 ceil 使其工作,但有人可以向我解释一下吗?
var_dump((int)ceil(39.3 * 100.0));//返回3930
解决方案
这是因为以 10 为底的有限表示的数字在 PHP 使用的浮点表示中可能有也可能没有精确表示.
见
<前>>php -r "echo var_dump(sprintf('%.40F', 39.3 * 100.0));"字符串(45) "3929.9999999999995452526491135358810424804688"由于 int
总是将数字向下舍入,因此表示中的一个小错误会使转换将其向下舍入一个您所期望的数字.
考虑使用 round
代替.
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
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
解决方案
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.
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.
Consider using round
instead.
这篇关于浮点到 int 类型转换的 PHP 意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!