vurentjie Posted April 11, 2009 Share Posted April 11, 2009 hi, i have a calculation that checks for minor cent precision differences across a number of payments. there is a monthly allowance and payments are distributed according to a pro-rata calculation and should add up to the monthly allowance... sometimes it is out by a cent or fraction of a cent so i thought i could check the difference between the allowance and the total that has been paid, //basic calc $diff = $allowance - $total_paid; if($diff >0).... if($diff <0)... the actual arithmetic is simple enough but i am getting precision errors if i echo it out i can get the following //without applying any rounding 2835.75 - 2835.75 = 4.54747350886E-13 any advice? i calculate the total_paid in a loop loop start $total_paid += $payment; //$payment does NOT get rounded either loop end the allowance is a figure a get from the database i cast this value to float before using it, but it is only there for checking against really. i only round figures after all calculations and only for display with php's number_format. Quote Link to comment https://forums.phpfreaks.com/topic/153592-float-precision-error/ Share on other sites More sharing options...
PFMaBiSmAd Posted April 11, 2009 Share Posted April 11, 2009 http://www.php.net/manual/en/book.bc.php Quote Link to comment https://forums.phpfreaks.com/topic/153592-float-precision-error/#findComment-807090 Share on other sites More sharing options...
Daniel0 Posted April 11, 2009 Share Posted April 11, 2009 Store the values as cent instead of dollars. You can never be guaranteed accurate representations of floating point numbers using a computer. Quote Link to comment https://forums.phpfreaks.com/topic/153592-float-precision-error/#findComment-807104 Share on other sites More sharing options...
vurentjie Posted April 11, 2009 Author Share Posted April 11, 2009 already have error_reporting on...one of the first things I set when developing... Store the values as cent instead of dollars Actually instead of rands. But yes that is gonna be the fix I reckon...it is definitely a precision error. Such a simple solution - wish I had thought of that... Will check in later... Quote Link to comment https://forums.phpfreaks.com/topic/153592-float-precision-error/#findComment-807106 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.