Home > Backend Development > PHP Tutorial > PHP之浮点数计算比较以及取整数不准确的解决办法_PHP

PHP之浮点数计算比较以及取整数不准确的解决办法_PHP

WBOY
Release: 2016-05-30 08:46:18
Original
944 people have browsed it

php有意思的现象,应该是很多编程语言都会有这样的现象。这个是因为计算机的本身对浮点数识别的问题.....下面通过代码给大家展示下:

$f = 0.58; 
var_dump(intval($f * 100 *100)); //结果5799 
var_dump((float)($f * 100 *100)); //结果5800 
echo (int)((0.1+0.7)*10); //结果7 
echo (float)((0.1+0.7)*10); //结果8 

<&#63;php 
$a = 0.1; 
$b = 0.7; 
var_dump(($a + $b) == 0.8); 
//打印出来的值居然为 boolean false 
<&#63;php 
$a = 0.1; 
$b = 0.7; 
var_dump(bcadd($a,$b,2) == 0.8);// bool true 
Copy after login

再次需注意的是在浮点数计算的时候,切记不要把浮点数转换成整形,否则会出现不可能预估的错误。

以上代码就是PHP之浮点数计算比较以及取整数不准确的解决办法。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template