向用户显示包括金钱计算在内的总金额 [英] Displaying total amount including money calculations to user

查看:52
本文介绍了向用户显示包括金钱计算在内的总金额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

注意:我已经在使用小数.小数

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

因此,我似乎是不正确的.克服此问题的最佳方法是什么?(一般来说,但是python特定的方法也有帮助)

Therefore i appear to be incorrect. What is the best way to overcome this? (I mean generally, but python specific methods will help too)

推荐答案

使用 decimal模块以获得正确计算的数学.您可以对其进行设置,以便每个值将自动使用两个小数位.

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.

这篇关于向用户显示包括金钱计算在内的总金额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆