Gun*_*jan 9 python decimal rounding ceil
有没有办法在python中获得高精度Decimal的ceil?
>>> import decimal;
>>> decimal.Decimal(800000000000000000001)/100000000000000000000
Decimal('8.00000000000000000001')
>>> math.ceil(decimal.Decimal(800000000000000000001)/100000000000000000000)
8.0
Run Code Online (Sandbox Code Playgroud)
math对值进行舍入并返回非精确值
Mar*_*son 22
获取Decimal实例的上限的最直接方法x
是使用x.to_integral_exact(rounding=ROUND_CEILING)
.这里没有必要弄乱上下文.请注意,这会在适当的位置设置Inexact
和Rounded
标记; 如果你不想触摸标志,请x.to_integral_value(rounding=ROUND_CEILING)
改用.例:
>>> from decimal import Decimal, ROUND_CEILING
>>> x = Decimal('-123.456')
>>> x.to_integral_exact(rounding=ROUND_CEILING)
Decimal('-123')
Run Code Online (Sandbox Code Playgroud)
与大多数Decimal方法不同,to_integral_exact
和to_integral_value
方法不受当前上下文精度的影响,因此您不必担心更改精度:
>>> from decimal import getcontext
>>> getcontext().prec = 2
>>> x.to_integral_exact(rounding=ROUND_CEILING)
Decimal('-123')
Run Code Online (Sandbox Code Playgroud)
顺便说一句,在Python 3.x中,math.ceil
它完全按照您的意愿工作,除了它返回一个int
而不是一个Decimal
实例.这是有效的,因为math.ceil
Python 3中的自定义类型是可重载的.在Python 2中,math.ceil
只需将Decimal
实例转换为float
第一个,可能在流程中丢失信息,因此最终可能会得到不正确的结果.
小智 5
x = decimal.Decimal('8.00000000000000000000001')
with decimal.localcontext() as ctx:
ctx.prec=100000000000000000
ctx.rounding=decimal.ROUND_CEILING
y = x.to_integral_exact()
Run Code Online (Sandbox Code Playgroud)