PHP floating point accuracy problem

Source: Internet
Author: User
Tags modulus square root

This period of time to maintain a similar group purchase system, the need to process orders, it will inevitably deal with the amount of PHP is a lot of the pit was my hard stepping on ~ ~

First we need to know the representation of floating-point numbers (IEEE 754):

In short, you bury a pit and wait for you to jump. For example, when handling floating-point addition and subtraction

<? PHP Echo (53.55-(3.67+49.88)); // -7.105427357601E-15?>

There is wood feel deeply malicious, but also PHP according to standard execution can only be circuitous forward;

Solution:

Bcmath Arbitrary Precision Mathematics

    • BC Math Functions
      • Bcadd-add arbitrary precision numbers
      • Bccomp-compare arbitrary precision numbers
      • Bcdiv-divide arbitrary precision numbers
      • Bcmod-get modulus of an arbitrary precision number
      • bcmul-multiply arbitrary Precision Number
      • Bcpow-raise an arbitrary precision number to another
      • Bcpowmod-raise an arbitrary precision number to another, reduced by a specified modulus
      • Bcscale-set Default scale parameter for all BC math functions
      • Bcsqrt-get the square root of an arbitrary precision number
      • Bcsub-subtract one arbitrary precision number from another

It's also very simple to use, for example

<? PHP // Echo (53.55-(3.67+49.88)); Echo (floatval(bcsub(bcadd(3.67,49.88), 53.55));
-0?>

Although-0 but also the effect of processing achieved,

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

PHP floating point accuracy 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.