如何将Python十进制数舍入到2位小数? [英] How to round a Python Decimal to 2 decimal places?
问题描述
>>> from decimal import Decimal
>>> a =十进制('1.23456789')
>>>类型(round(a,2))
在小数模块中,我看到了一些与舍入有关的事情:
- ROUND_05UP
- ROUND_CEILING
- ROUND_DOWN li> ROUND_FLOOR
- ROUND_HALF_DOWN
- ROUND_HALF_EVEN
- ROUND_HALF_UP
ROUND_UP - Rounded
我认为这些实际上没有给我想要的东西(或我的错误在这里?)。
所以我的问题:是否有人知道我如何可靠地将Python十进制数舍入到2位小数,以便我有一个十进制数继续?所有的提示都是值得欢迎的! /library/decimal.html#decimal.Decimal.quantize> quantize()
method :
>>>进口十进制
>>> decimal.getcontext()。prec = 20
>>> a = decimal.Decimal(321.12345)
>>> a
十进制('321.12344999999999117790139280259609222412109375')
>>> TWO_PLACES = decimal.Decimal(0.01)
>>> a.quantize(TWO_PLACES)
十进制('321.12')
I've got a python Decimal (a currency amount) which I want to round to two decimal places. I tried doing this using the regular round() function. Unfortunately, this returns a float, which makes it unreliable to continue with:
>>> from decimal import Decimal
>>> a = Decimal('1.23456789')
>>> type(round(a, 2))
<type 'float'>
in the decimal module, I see a couple things in relation to rounding:
- ROUND_05UP
- ROUND_CEILING
- ROUND_DOWN
- ROUND_FLOOR
- ROUND_HALF_DOWN
- ROUND_HALF_EVEN
- ROUND_HALF_UP
- ROUND_UP
- Rounded
I think that none of these actually give what I want though (or am I wrong here?).
So my question: does anybody know how I can reliably round a Python Decimal to 2 decimal places so that I have a Decimal to continue with? All tips are welcome!
You could use the quantize()
method:
>>> import decimal
>>> decimal.getcontext().prec = 20
>>> a = decimal.Decimal(321.12345)
>>> a
Decimal('321.12344999999999117790139280259609222412109375')
>>> TWO_PLACES = decimal.Decimal("0.01")
>>> a.quantize(TWO_PLACES)
Decimal('321.12')
这篇关于如何将Python十进制数舍入到2位小数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!