php浮点数计算比较及取整不准确解决方法,取整不准确
php有意思的现象,应该是很多编程语言都会有这样的现象。这个是因为计算机的本身对浮点数识别的问题.....
[php] view plaincopy
- $f = 0.58;
- var_dump(intval($f * 100 *100));
- var_dump((float)($f * 100 *100));
- echo (int)((0.1+0.7)*10);
- echo (float)((0.1+0.7)*10);
[php] view plaincopy
-
- $a = 0.1;
- $b = 0.7;
- var_dump(($a + $b) == 0.8);
[php] view plaincopy
-
- $a = 0.1;
- $b = 0.7;
- var_dump(bcadd($a,$b,2) == 0.8);
在浮点数计算的时候,切记不要把浮点数转换成整形,否则会出现不可能预估的错误。
所以永远不要相信浮点数结果精确到了最后一位,也永远不要比较两个浮点数是否相等。
Statement:The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn