为什么`intval(19.9 * 100)'等于`1989`? [英] Why does `intval(19.9 * 100)` equal `1989`?
本文介绍了为什么`intval(19.9 * 100)'等于`1989`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
男孩,这个真的很奇怪.我希望下面的代码可以打印1990,但是可以打印1989!
Boy, this one is really weird. I expect the following code to print 1990, but it prints 1989!
$val = '$19.9';
$val = preg_replace('/[^\d.]/','',$val);
$val = intval($val * 100);
echo $val;
这到底是怎么回事?
和此代码:
$val = '$19.9';
$val = preg_replace('/[^\d.]/','',$val);
echo $val . "<br>";
$val = $val * 100;
echo $val . "<br>";
$val = intval($val);
echo $val;
打印:
19.9
1990
1989
为什么intval(1990)
等于1989
???
推荐答案
这是PHP和许多其他语言中的浮点数固有的精度问题.此错误报告在强制转换为int的背景下对此进行了一些讨论:
This is a precision issue inherent to floating point numbers in PHP, and lots of other languages. This bug report discusses it a bit, in the context of casting as an int:
http://bugs.php.net/bug.php?id=33731
改为尝试round($val * 100)
.
这篇关于为什么`intval(19.9 * 100)'等于`1989`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文