Reputation: 2668
I read in a Python book saying that in financial world, sometimes it'd be better using quantize() and decimal module to round off floating-point numbers. An example is given in the book as below,
from decimal import Decimal
price = Decimal('19.99')
tax = Decimal('0.06')
total = price + (price * tax)
penny = Decimal('0.01')
total.quantize(penny)
But why not
round(19.99+19.99*0.06,2)
When does quantize() outperform round() in terms of numerical accuracy? Anyone can provide an example?
Upvotes: 0
Views: 1289
Reputation: 15638
I don't think that the main reason for using Decimal (and quantize) is speed: it's accuracy. From the docs:
Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.
If you are dealing with big numbers and you require the result to be correct up to 1 cent, then the accuracy (with floating point arithmetics) may be an issue.
Upvotes: 2