Displaying total amount including money calculations to user

僤鯓⒐⒋嵵緔 提交于 2021-01-05 12:15:48

问题


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)


回答1:


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.



来源:https://stackoverflow.com/questions/12938935/displaying-total-amount-including-money-calculations-to-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!