One of the easy ways to get around this is to use the BC Math
.
Thus the ((33 * 0.8) - 26.4)
would be:
bcscale(2);
echo bcsub(bcmul('33', '0.8'), '26.4');
// O resultado será de `0.00`.
Test this.
The bcsub()
will subtract the 26.4
of the resulting value of bcmul()
. The bcmul()
is responsible for multiplying the 33
for 0.8
, containing 2 digits after the comma, defined bybcscale(2);
, in this case.
In the absence of a definition of bcscale
standard 0 will be used, making 5.7 - 4.3 = 1 instead of 1.4
, for example.
If you want to compare values you can use bccomp()
, it works in a similar way to spacecraft operator (<=>
), where you return 0
if it is equal, -1
the left side is larger or 1
if the right side is larger, Test this.
echo bccomp(bcmul('33', '0.8', 2), '26.4', 2);
// O resultado será de `0`.
All documentation of the bc*
is in http://php.net/manual/en/ref.bc.php, as indicated by @Anderson Carlos Woss.
Start by reading the documentation. She explains well why it happens.
– Woss
Maybe I can help you: http://stackoverflow.com/questions/13128769/simple-math-with-decimals-in-php
– Aline
if you still want to use 0.8 then use echo number_format(((33 * 0.8) - 26.4),0) and if you need 2 decimal places use echo number_format((33 * 0.8) - 26.4),2)
– user60252
@Andersoncarloswoss I also wanted to know the reason for this to happen too, it’s just any calculation, but when it’s decimal by the percentage returns this value
– Jeferson Assis
Testa http://answall.com/a/188514/3635 and let me know.
– Guilherme Nascimento
Moderator note: Although the linked question as duplicate is marked with the Javascript tag, the problem (and the answer) is universal for any language in the use of floating point numbers.
– bfavaretto
@Leocaracciolo, giving how number_format works perfectly, but I wonder why php gives this result instead of 0
– Jeferson Assis
@bfavaretto I had reopened because he wants to know how to "solve", including I had linked all these the first time I scored as dup, but I agree with you, anyway wanted to leave a reply, I just don’t know if it is the best solution for PHP.
– Guilherme Nascimento
Thank you all very much, it was more to know the reason, because until then I had never seen anything like it.
– Jeferson Assis
Just to confirm, you realize that
3.5527136788005E-15
is practically zero, right?– bfavaretto
Yes, but always when compared with the correct value returned
false
, the other way I quoted in the example works perfectly.– Jeferson Assis