PHP's floor function problem.

Source: Internet
Author: User


Recently, I was writing a project about finance. It involves a lot of money decimal problem. Once the floor wanted to achieve a downward rounding to two decimal places, suddenly found the following code is not normal.

$money =271.28;echo $money =floor ($money *pow (10,2))/100
I was surprised to find out that the output was not 271.28 but271.27!

Later looked at a lot of information, on the PHP official web site to see this point:

the precision of floating-point numbers is limited,a rational number that can be accurately expressed in decimal, such as0.1or0.7, no matter how many mantissa can be used in the internal binary precision representation, so can not lose a little bit of precision in the case of conversion to binary format. This can result in confusion: for example,Floor ((0.1+0.7) *10)usually returns7Instead of the expected8, because the internal representation of the result is actually similar7.9999999999999991118 .... so never believe that the floating-point number is accurate to the last one, and never compare two floating-point numbers for equality.

Then I printed the result of the above operation:

printf ("%.12f", $money *pow (10,2));
The findings are:27127.999999999996

It turned out to be a precision problem. A unified solution has not yet been found. I only add in the code logic

if ($money-round ($money, 2) < 0.00001) {}else{$money =floor ($money *pow (10,2))/100;}
To avoid data re-processing with two bits of precision.

If someone knows another way to achieve my above function (two digits after the decimal point, no matter what the third place is discarded), please teach me.


PHP's floor function problem.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.