Floating point rounding error php ...how can I make sure it works correctly? -
I have the following function that determines whether I have paid the sale completely, I do not remember that I Why, but it is still working and I do not remember why I had to do this.
function_payments_cover_total () {/ Get_payments is a list of payment amount such as: //10.20, 10.21, or 10.1010101101 (maximum 10 decimals) $ total_payments = 0; Foreign Currency ($ this-> Sales_lib- & gt; get_payments () $ form of payment) {$ total_payments + = $ payment ['payment_mount']; } // to_currency_no_money round the total if at two decimal places (to_currency_no_money ($ this-> sale_lib- & gt; get_total ()) - $ total_payments) & gt; 1e-6)) {return false; } Back true; } I am wondering if there is ever a case where this function will return false due to a rotating error when it should not be.
I have a question about the main part:
& gt; 1e-6 I think before I was, but in some cases it was causing the problem.
& gt; I think that whatever you have been mentioned on the help page, you are doing this
To quote it directly:
To test the floating point value for equality, due to rounding there is an upper limit on relative error. This value is known as machine apocillon or unit goallof, and is the smallest acceptable difference in calculation.
$ a and $ b are equal to 5 digits of exact & Lt ;? Php $ a = 1.23456789; $ B = 1.23456780; $ Apicilon = 0.00001; If (abdomen ($ a- $ b) & lt; $ epsilon) {echo "true"; }? & Gt; In your case: (to_currency_no_money ($ this-> sales_lib-> get_total ()) - $ total_payments) gt; ; 1e-6 Relative error due to rounding should not be greater than 1e-6 or 0.000001 If you are not sure about the left operand, then the correct 100% is more than time, then you should add abs () for correctness. $ Relative_error = to_currency_no_money ($ this- & gt; sales_lib- & gt; get_total ()) - $ total_payments; If (Ab ($ relative_arrow)> 1e-6) {return false} return is true;
Comments
Post a Comment