在Python 3中,小数点后2位货币 [英] Decimals to 2 places for money in Python 3

查看:141
本文介绍了在Python 3中,小数点后2位货币的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用十进制模块使小数位数保持在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.

推荐答案

在赚钱时通常需要尽可能地限制精度,以便乘法等操作不会汇总舍入误差。在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() a Decimal to any precision you want:

unit_price = decimal.Decimal('8.0107')
quantity = decimal.Decimal('0.056')
price = unit_price * quantity
cents = decimal.Decimal('.01')
money = price.quantize(cents, decimal.ROUND_HALF_UP)

这篇关于在Python 3中,小数点后2位货币的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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