A catastrophic bug caused by PHP accuracy calculation

Source: Internet
Author: User

When it comes to maintaining an older financial project, we find that the calculation of precision is simple and rough, first look at the code snippet:

if ($accountInfo [' Account_money '] < $repayMoney) {                rollback ();                return false;}

As shown in the code fragment variable above, the above code mainly compares account balances and repayments, both double-precision floating-point numbers, slightly modified code, so that we can see some of the output is more intuitive

if ($accountInfo [' Account_money '] < $repayMoney) {                echo "{$accountInfo [' Account_money ']}\n\r";                echo "{$repayMoney}\n\r";                Rollback ();                return false;}

Run as above code get as result

Two numbers are 1333.35, if according to the above logic, should not enter the if body, but the result is the opposite, the if body and echo out of two values, by consulting the relevant API found that the accuracy of the PHP operation, the direct +,-, *,/,<,> and other operations lost precision , so the result is not as you would like, here you are, in PHP for precision operations, you should call the relevant API, such as BC Math.

A catastrophic bug caused by PHP accuracy calculation

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.