Warnings about the precision of floating-point numbers in PHP

Source: Internet
Author: User
Warning for floating point accuracy in PHP

This is a hint from PHP document:


A simple decimal score like 0.1 or 0.7 cannot be converted to an internal binary format without losing a little bit of precision.

Floor ((0.1 + 0.7) *)? return 7 instead of 8,

(int) ((0.1 + 0.7) * 10)? Returns 7 instead of 8.

?

The explanation for this phenomenon is "because the internal representation of the result is actually similar to 7.9".

?

So the result is:

So never believe that the floating-point number is accurate to the last one, and never compare two floating-point numbers for equality.

Never cast an unknown fraction to an int.

?

(int) Round (0.1 + 0.7) * 10) This seems to be safe.

The BC math function is used for numerical accuracy when there is a large number of multiplication or if the median value is float type.

?

  • Related Article

    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.