如何舍入 Python Decimal 实例 [英] How to round Python Decimal instance
问题描述
如何将 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
以获得您想要的.
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屋!