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? 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; 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 Link to comment https://forums.phpfreaks.com/topic/283971-floating-point-subtraction-error/#findComment-1458590 Share on other sites More sharing options...
Irate Posted November 16, 2013 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); 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! 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. Link to comment https://forums.phpfreaks.com/topic/283971-floating-point-subtraction-error/#findComment-1458596 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.