我有一段代码,它正在查看来自一些计算的数字,并且非常精确,该代码试图根据原始数字(在计算之前)找出正确的精度。然后,它使用以下内容应用舍入:
with localcontext() as ctx:
ctx.prec = 5 # simplification for the sake of this example
my_figure = +my_figure只要my_figure不等于零,一切都是好的。这根本不会影响零,所以它的精度与以前相同(本例中不是5)。
my_figure = Decimal('0.0000...') # 0E-30, it comes from some calculations, not assigned like that
with localcontext() as ctx:
ctx.prec = 5 # simplification for the sake of this example
my_figure = +my_figure
print my_figure # I get 0E-30, no rounding applied, I was expecting 0.0000有没有合适的方法来做这件事,也会影响到零?
发布于 2013-11-27 21:48:40
Decimal.normalize做你想做的事了吗?它不会将精度保持为5dp,但至少它会将0E-30压缩为合理的精度。
https://stackoverflow.com/questions/13625061
复制相似问题