Incorrect multiplication calculation [duplicate]

5

For some reason when I make the calculation by multiplying by a floating value, PHP always returns the wrong value.

Example:

echo ((33 * 0.8) - 26.4);

result: 3.5527136788005E-15

But the expected result would be 0

I could not find any answer to this problem, because if I perform the calculation to get 80% of the value differently it works.

Example:

echo (((33 * 80) / 100) - 26.4);

result: 0
    
asked by anonymous 07.03.2017 / 18:44

3 answers

7

As you already have the answer on how to circumvent the situation, I'll leave here the > that explains why this happens.

  

Floating-Point Number Accuracy

     

Floating-point numbers have limited precision. Although it depends on the system, PHP generally uses the IEEE 754 dual-precision format, which will bring maximum precision due to rounds of the order of 1.11e-16. Uncommon math operations may cause major errors, and of course, error propagation must be considered when multiple operations are performed.

     In addition, rational numbers that have exact representation on base 10 numbers, such as 0.1 or 0.7, do not have exact floating-point representation in base 2, the format used internally, regardless of the size of the mantissa. So there is no conversion to the internal format without a small loss of precision. This can cause confusing results: for example, floor ((0.1 + 0.7) * 10) will usually return 7, instead of the expected result 8, because the final internal representation will look something like 7.9999999999999991118 ....

     

So, never trust results with floating-point numbers to the last house, and never compare floating-point numbers in equalities. If you really need high precision, you can use arbitrary precision math functions and are available.

For a "simple" explanation of this question, see the »floating point guide , which also has the alternate title of "Because my numbers do not add up right?".

    
07.03.2017 / 18:56
4

The Anderson answer explains why, as well as these questions:

Then to try to adjust you can use the function round , this will round the value, like this:

$foo = (33 * 0.8) - 26.4;

echo round($foo);
  

link

Set the second parameter to the precision you want:

$foo = (33 * 0.8) - 26.4;

echo round($foo, 3);
    
07.03.2017 / 19:48
3

One of the easiest ways to get around this is to use BC Math .

In this way ((33 * 0.8) - 26.4) would be:

bcscale(2);
echo bcsub(bcmul('33', '0.8'), '26.4');

// O resultado será de '0.00'.

Try this.

The bcsub() will subtract the 26.4 from the value resulting from the bcmul() . The bcmul() is responsible for multiplying the 33 by 0.8 , containing 2 digits after the comma , defined by bcscale(2); , in this case.

  

In the absence of the definition of bcscale will be used the default 0, making 5.7 - 4.3 = 1, instead of 1.4 , for example.

If you want to compare values you can use bccomp() , it works similarly to

07.03.2017 / 19:21