Shackrock
Shackrock

Reputation: 4701

php adds my numbers to 10^-16 instead of ZERO (0)

I have a function that adds a lot of numbers with decimals.... FLOAT numbers from MySQL DB.

Right now, I have the issue that sometimes they will add to ridiculously small numbers like -1.11022302463E-16, instead of zero. Any ideas?

By the way, All my numbers I'm adding are monetary, so they are all like : XXX.XX ....

Thanks

Upvotes: 1

Views: 170

Answers (2)

dqhendricks
dqhendricks

Reputation: 19251

read this section of the php manual, especially the precision warning.

http://www.php.net/manual/en/language.types.float.php

at the bottom you will see links to functions you can use for high precision math

Upvotes: 1

Johan
Johan

Reputation: 76597

As suggested by @BoltClock, change all the float fields to decimal(10,2) fields in your database where they are used for monetary values. Float suffers from rounding problems like the ones you describe.

If you do all your adding inside the database you will not suffer any rounding errors.

You can add numbers by doing a

UPDATE table1 SET money1 = money1 + 10.20 WHERE table1.id = 10

Substituting the constants for parameters.

Upvotes: 1

Related Questions