本文介绍了浮点到 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 意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End



大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)