Ruby rounding issues
I have written some code which extracts and invoice from various hashes, arrays, arrays of hashes, etc. In the i开发者_JAVA技巧nvoice, I am to sub-total the items sold, add provincial sales tax (Canadian, and GST to come up with a grand total. Have all of that. I have a small block to deal with the formatting:
def currency amount
sprintf("$%.2f",amount)
end
which of course puts the amount as a float with a dollar sign. I am having issues with rounding. One of my invoices adds to one penny more than it should. I understand the whole floating point precision thing, that is not my issue. My instructor says that I need to modify the currency block. I have tried multiplying my values by 100, and then dividing by 100 after I use currency:
puts "GST (#{tax(GST*100)}%) :#{currency(gst_total/100)}"
but that of course formats everything with floating numbers again, and the same issue is there. How can I modify this?
You may need to round your items or tax values before summing them. For example, RoundCents(1.004 * 3) is 3.01, but RoundCents(1.004) * 3 is 3.00.
Or, you may be a victim of banker's rounding.
精彩评论