Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP subtracting numbers strangely - returning long float values

Tags:

php

I'm calculating fees (monetary) for something and PHP is behaving strangely when the amount is supposed to be 0.00. It's giving the final result as a floating number, not 0 which it should be.

In My database I have the following table

id   |  transaction_total   |    charge_fees   |  deposit_fee   |   amount_to_customer   |   fees_minus_total_difference

So when I go to check to make sure that the fees + amount paid - total = 0.00

(96.54 + .25 + 3.20 - 99.99) = 1.4210854715202E-14

Why is the result a floating number and not actually zero? The numbers are originally more decimal places, but I used number_format to put it into 2 places. Ex, charge fees may actually be 3.19987

number_format(3.19971,2,'.','')  //equals 3.20

When I save this in my database it displays as 3.20. When I use it in the computation for the total/fee check, the result is not zero, albeit close.

like image 710
user1443519 Avatar asked Sep 10 '26 14:09

user1443519


1 Answers

Computers store numbers in binary, so when you try to represent a decimal number you may lose precision. That is what is happening here.

Some languages have exact-precision types, but PHP, unfortunately, does not. It does provide you with both BC Math and GMP, though. Using those here seems overkill, though. Using BC, you could do this though:

bcsub(bcadd(bcadd('96.54','0.25',2),'3.20',2),'99.99',2) = 0

Notice that you have to specify the number of decimal points (2) here also.

Generally, using floats and double for finances is frowned upon, but with PHP it does seem like the simpler option.I suggest you just round your number using round() to the number of decimal places of your input.

round(96.54 + .25 + 3.20 - 99.99,2) = 0
like image 131
kba Avatar answered Sep 12 '26 03:09

kba