使用python 3.6
https://docs.python.org/3.6/library/decimal.html
我可以看到我们可以指定舍入和精度,但是只能通过设置上下文来全局指定.
如何为特定的Decimal实例执行此操作?
像这样的伪代码:
myNumber = Decimal(1.101901)
roundedNumber = myNumber.toFixed(2,ROUND_DOWN)
# expected result ==> 1.10
roundedNumber = myNumber.toFixed(2,ROUND_UP)
# expected result ==> 1.11
因此,我可以使用所需的舍入和精度来解析每个数字.
最佳答案
使用方法Decimal.quantize.
from decimal import *
myNumber = Decimal(1.101901)
roundedNumber = myNumber.quantize(Decimal('1.00'),rounding=ROUND_DOWN) # 1.10
roundedNumber = myNumber.quantize(Decimal('1.00'),rounding=ROUND_UP) # 1.11