Reasons for PHP floating point calculation errors

(*-*)浩
Release: 2023-02-26 20:00:02
Original
2593 people have browsed it

Reasons for PHP floating point calculation errors

Example: (Recommended learning: PHP video tutorial)

echo intval(0.58*100);//结果为57
echo intval((0.1 + 0.7) * 10);//结果为7
Copy after login

The reason for this is that the computer Some floating-point numbers cannot be accurately represented internally in binary, just like we cannot accurately represent 10/3 in decimal.

The internal representation of floating-point numbers in the computer: IEEE 754. If you don’t understand, look it up yourself Information

You can also refer to this article by Bird Brother: http://www.laruence.com/2013/03/26/2884.html

<?php
echo intval(0.58*100);//57,注意啦
echo &#39;<br/>&#39;;
echo intval(bcmul(0.58, 100));//58
echo &#39;<br/>&#39;;
echo floor(strval(0.58*100));//58
echo &#39;<br/>&#39;;
echo (int)(0.58 * 1000/10);//58
echo &#39;<br/>&#39;;
echo intval((0.1 + 0.7) * 10);//7,注意啦
echo &#39;<br/>&#39;;
echo intval(bcadd("0.1", "0.7",1) * 10);  //8
?>
Copy after login

Let’s look at another example

<?php
if((0.1 + 0.7) == 0.8){
	echo &#39;相等&#39;; 
}else{
	echo &#39;不相等&#39;; //这里输出
}
echo &#39;<br />&#39;;
$a = 0.1 + 0.7;
echo $a; //0.8
echo &#39;<br/>&#39;;
if($a == 0.8){ 
	echo &#39;一天一小步&#39;;
}else{
	echo &#39;一年一大步&#39;; //这里输出
}
echo &#39;<br/>&#39;;
if(strval($a) == 0.8){
	echo &#39;一天一小步&#39;; //这里输出
}else{
	echo &#39;一年一大步&#39;; 
}
echo &#39;<br/>&#39;;
if(bcadd(0.1, 0.7,1) == 0.8){
	echo &#39;一天一小步&#39;; //这里输出
}else{
	echo &#39;一年一大步&#39;;
}
/*
结果:
不相等
0.8
一年一大步
一天一小步
一天一小步
*/
?>
Copy after login

$a = 0.00...00(n zeros)1 0.7; When using strval to obtain the value of $a, the result of whether $a and 0.8 are equal will be caused by the different number of n zeros. Different

The bcadd function will add 2 numbers, depending on how many decimals you choose to keep and discard the following decimals

Look at a division example:

<?php
echo 160500643816367088/10;//1.6050064381637E+16
echo &#39;<br/>&#39;;
echo intval(160500643816367088/10);//16050064381636710
echo &#39;<br/>&#39;;
echo bcdiv(160500643816367088,10);//16050064381636708
?>
Copy after login

So for sensitive data such as floating point numbers to calculate amounts, it is recommended to use PHP's BC function

The above is the detailed content of Reasons for PHP floating point calculation errors. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
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