Python 3 中钱的小数保留到 2 位
如何使用 decimal
模块让小数保留 2 位来表示货币?
我已经设定了精度,几乎其他一切都该死,但遇到了失败。
How do I get my decimals to stay at 2 places for representing money using the decimal
module?
I've setting the precision, and damn near everything else, and met with failure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在处理金钱时,您通常希望尽可能晚地限制精度,这样乘法之类的事情就不会聚合舍入误差。在 python 2 和 3 中,您可以将
.quantize()
为您想要的任何精度的Decimal
:When working with money you usually want to limit precision as late as possible so things like multiplication don't aggregate rounding errors. In python 2 and 3 you can
.quantize()
aDecimal
to any precision you want:程序员对金钱的误解:
Falsehoods programmers believe about money:
除了用于舍入操作的常量之外,接受的答案大多是正确的。您应该使用
ROUND_HALF_UP
而不是ROUND_05UP
进行货币操作。根据 文档:仅当百位数字为 5 或 0 时,使用
ROUND_05UP
才会向上舍入(对于正数),这对于货币数学来说是不正确的。以下是一些示例:
The accepted answer is mostly correct, except for the constant to use for the rounding operation. You should use
ROUND_HALF_UP
instead ofROUND_05UP
for currency operations. According to the docs:Using
ROUND_05UP
would only round up (for positive numbers) if the number in the hundredths place was a 5 or 0, which isn't correct for currency math.Here are some examples:
解决此问题的一种方法是将货币值以整数形式存储为美分,并且仅在打印值时转换为十进制表示形式。这称为定点算术。
One way to solve this is to store money values in cents as integers, and only convert to decimal representation when printing values. This is called fixed point arithmetic.
您只需将精度设置为 2(第一行),所有内容将使用不超过 2 位小数,
仅供比较:
You just have to set the precision to 2 (the first line) and them everything will use no more than 2 decimal places
Just for comparison: