Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When -11.5 plus 11.5 equals float(2.8421709430404E-14) [duplicate]

Tags:

php

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?

like image 880
Mark Smith Avatar asked Aug 16 '12 15:08

Mark Smith


1 Answers

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)
);
like image 188
Inoryy Avatar answered Oct 23 '22 18:10

Inoryy