如何舍入 Python Decimal 实例 [英] How to round Python Decimal instance

查看:42
本文介绍了如何舍入 Python Decimal 实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将 Python Decimal 实例四舍五入到特定位数,同时四舍五入到最接近的小数?

我尝试使用 docs,并在 以前的答案,但尽管尝试了不同的 ROUND_ 选项,但它似乎没有正确舍入.我也试过设置 getcontext().prec,但这似乎只能控制整个数字中的总位数,而不仅仅是小数.

例如我正在尝试执行以下操作:

assert Decimal('3.605').round(2) == Decimal('3.61')assert Decimal('29342398479823.605').round(2) == Decimal('29342398479823.61')assert Decimal('3.604').round(2) == Decimal('3.60')assert Decimal('3.606').round(2) == Decimal('3.61')

解决方案

我认为您需要使用 decimal.ROUND_HALF_UP 选项来quantize 以获得您想要的.

<预><代码>>>>对于 x in ('3.605', '29342398479823.605', '3.604', '3.606'):打印 x, repr(Decimal(x).quantize(Decimal('.01'), decimal.ROUND_HALF_UP))3.605 十进制('3.61')29342398479823.605 十进制('29342398479823.61')3.604 十进制('3.60')3.606 十进制('3.61')

How do I round a Python Decimal instance to a specific number of digits while rounding to the nearest decimal?

I've tried using the .quantize(Decimal('.01')) method outlined in the docs, and suggested in previous answers, but it doesn't seem to round correctly despite trying different ROUND_ options. I've also tried setting getcontext().prec, but that seems to only control the total number of digits in the entire number, not just the decimals.

e.g. I'm trying to do something like:

assert Decimal('3.605').round(2) == Decimal('3.61')
assert Decimal('29342398479823.605').round(2) == Decimal('29342398479823.61')
assert Decimal('3.604').round(2) == Decimal('3.60')
assert Decimal('3.606').round(2) == Decimal('3.61')

解决方案

I think you need to use the decimal.ROUND_HALF_UP option to quantize to get what you want.

>>> for x in ('3.605', '29342398479823.605', '3.604', '3.606'):
    print x, repr(Decimal(x).quantize(Decimal('.01'), decimal.ROUND_HALF_UP))

3.605 Decimal('3.61')
29342398479823.605 Decimal('29342398479823.61')
3.604 Decimal('3.60')
3.606 Decimal('3.61')

这篇关于如何舍入 Python Decimal 实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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