Python降低精度为零

时间:2012-11-29 11:44:08

标签: python decimal rounding zero

我有一段代码正在查看来自某些计算的数据并且非常精确,并且代码试图根据原始数字(在计算之前)找出正确的精度。然后它使用以下方法应用舍入:

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

是否有任何正确的方式来影响零?

1 个答案:

答案 0 :(得分:0)

Decimal.normalize能做你想做的吗?它不会将精度保持在5dp,但至少它会将0E-30缩小到合理的状态。