Possible Duplicate:
PHP Math Precision
Best practice for working with currency values in PHP?
I really hope someone can help. I've been hitting my head against a brick wall on this one.
Here's the situation: I have a checkout which calculates the subtotal after discount to be -£11.50. There is then £11.50 delivery cost to add which IMHO should equal £0.
However when the calculation is run it returns a float 2.8421709430404E-14
In my debug efforts I have done this:
var_dump(
$build['total'], // float(-11.5)
$build['delivery'], // float(11.5)
(($build['total'])+($build['delivery'])) // float(2.8421709430404E-14)
);
However when I do a static calculation:
var_dump((-11.5 + 11.5)); // float(0)
Any ideas?
2.8421709430404E-14 is the closest to (but not equal to) zero number PHP can output. The reason it's not exactly 0 lies in the definition of floating point numbers - they're never fully precise.
If you need to work with sensible information that also contains fraction points, I suggest you bring it to integer by multiplying to the fraction.
So $100.54 becomes 10054. After all calculations are done you can then divide back to the fraction.
Example:
$build['total'] = -11.5;
$build['delivery'] = 11.5;
var_dump(
$build['total'], // float(-11.5)
$build['delivery'], // float(11.5)
(int)($build['total']*1000)+(int)($build['delivery']*1000) // int(0)
(int)(round($build['total'], 4)*1000)+(int)(round($build['delivery'], 4)*1000) // int(0)
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With