Home > Backend Development > PHP Tutorial > PHP floor function problem.

PHP floor function problem.

WBOY
Release: 2016-08-08 09:31:09
Original
1595 people have browsed it

Copy after login

I am currently writing a project about finance. There are a lot of decimal issues involved. Once when I used floor to round down to two decimal places, I suddenly found that the following code was abnormal.

$money=271.28;
echo $money=floor($money*pow(10,2))/100
Copy after login
I was surprised to find that the output was not 271.28 but 271.27!

Later I checked a lot of information and saw this on the php official website:

The precision of floating point numbers is limited, can be accurately expressed in decimal Rational numbers such as 0.1 or 0.7, no matter how many mantissas there are, cannot be accurately represented by the binary used internally, and therefore cannot be converted to binary format without losing a little bit of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, because the internal representation of the result is actually It is similar to 7.99999999999999991118.... So never believe that the floating point number result is accurate to the last digit, and never compare whether two floating point numbers are equal.

Later I printed the result of the above operation:

printf("%.12f", $money*pow(10,2));
Copy after login
found that the result was: 27127.999999999996

It turned out to be an accuracy problem. No unified solution has been found yet. I can only add

if ($money - round ( $money, 2 ) < 0.00001) {

}else{
$money=floor($money*pow(10,2))/100;
}
Copy after login
to the code logic to avoid reprocessing the data that has been accurate to two digits.

If anyone knows another way to implement the above function (accurate to two decimal places and discard whatever the third digit is), please let me know.

The above introduces the problem of PHP's floor function. , including relevant content, I hope it will be helpful to friends who are interested in PHP tutorials.

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