Home>Article>Backend Development> Reasons for PHP floating point calculation errors

Reasons for PHP floating point calculation errors

(*-*)浩
(*-*)浩 Original
2019-10-16 10:01:32 2516browse

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

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

'; echo intval(bcmul(0.58, 100));//58 echo '
'; echo floor(strval(0.58*100));//58 echo '
'; echo (int)(0.58 * 1000/10);//58 echo '
'; echo intval((0.1 + 0.7) * 10);//7,注意啦 echo '
'; echo intval(bcadd("0.1", "0.7",1) * 10); //8 ?>

Let’s look at another example

'; $a = 0.1 + 0.7; echo $a; //0.8 echo '
'; if($a == 0.8){ echo '一天一小步'; }else{ echo '一年一大步'; //这里输出 } echo '
'; if(strval($a) == 0.8){ echo '一天一小步'; //这里输出 }else{ echo '一年一大步'; } echo '
'; if(bcadd(0.1, 0.7,1) == 0.8){ echo '一天一小步'; //这里输出 }else{ echo '一年一大步'; } /* 结果: 不相等 0.8 一年一大步 一天一小步 一天一小步 */ ?>

$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:

'; echo intval(160500643816367088/10);//16050064381636710 echo '
'; echo bcdiv(160500643816367088,10);//16050064381636708 ?>

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!

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