compgeek83 Posted November 16, 2013 Share Posted November 16, 2013 $balance_due = $salesreceipt_grandtotal - $payments_applied; if $balance_due is 0 I get "5.6843418860808E-14" instead of 0. What can I do to return 0 instead of this error? Quote Link to comment https://forums.phpfreaks.com/topic/283971-floating-point-subtraction-error/ Share on other sites More sharing options...
Irate Posted November 16, 2013 Share Posted November 16, 2013 Not using floats but integers helps. This is not a problem specific to PHP, by the way. Try using this instead. $balance_due = (int) $salesreceipt_grandtotal - $payments_applied; Quote Link to comment https://forums.phpfreaks.com/topic/283971-floating-point-subtraction-error/#findComment-1458589 Share on other sites More sharing options...
compgeek83 Posted November 16, 2013 Author Share Posted November 16, 2013 that helped in a way, now I get "-0.64999999999998" instead of the error, if I echo out each variable they are identical though Quote Link to comment https://forums.phpfreaks.com/topic/283971-floating-point-subtraction-error/#findComment-1458590 Share on other sites More sharing options...
Solution Irate Posted November 16, 2013 Solution Share Posted November 16, 2013 The result you got in the first version is not an error, 5.6843418860808E-14 actually equals -0.64999999999998, it's just written in its exponential form. Try using the (int) statement twice, like this. $balance_due = ((int) $salesreceipt_grandtotal) - ((int) $payments_applied); Quote Link to comment https://forums.phpfreaks.com/topic/283971-floating-point-subtraction-error/#findComment-1458592 Share on other sites More sharing options...
compgeek83 Posted November 16, 2013 Author Share Posted November 16, 2013 Bingo, that works perfectly, thank you! Quote Link to comment https://forums.phpfreaks.com/topic/283971-floating-point-subtraction-error/#findComment-1458594 Share on other sites More sharing options...
Irate Posted November 16, 2013 Share Posted November 16, 2013 Bingo, that works perfectly, thank you! You're welcome. Also, I noticed that 5.68...E-14 is not -0.649..., I forgot that in the first code I provided, one of the results was already being converted to an int. So, for the record, 5.68...E-14 is close to -0.649..., but not equal to it. Sorry for the confusion. Quote Link to comment https://forums.phpfreaks.com/topic/283971-floating-point-subtraction-error/#findComment-1458596 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.