Note: I'm already using decimal.Decimal
What is the best way to perform and display calculations to the end user when you are required to output in the following rough style:
Item - £ 70.10
Item - £ 5.67
Item - £ 10.33
--------------
Total £ 86.10
I was always taught in maths as a kid to not round before your final answer, else you'll lose precision, but in this case if you don't it looks like we have calculation errors. as the calculation behind the display is not the same as the user would do from the numbers displayed to them.
EG:
My app will be doing: 70.1034 + 5.6693 + 10.333333333 = 86.1060333 (86.11 2dp)
My end user will be doing as above: 70.10 + 5.67 + 10.33 = 86.10
Therefore i appear to be incorrect. What is the best way to overcome this? (I mean generally, but python specific methods will help too)
Use the decimal
module to get math that works out correctly. You can set it so each value will automatically use two decimal places.
>>> decimal.getcontext().prec = 2
>>> decimal.Decimal(1)/decimal.Decimal(3)
Decimal('0.33')
When you're working with money, it's normal to lose precision at each intermediate calculation.