Python降低了零的精度

Python降低了零的精度,python,decimal,rounding,zero,Python,Decimal,Rounding,Zero,我有一段代码,它可以查看来自一些计算的数字,并且非常精确,该代码试图根据原始数字(在计算之前)计算出正确的精度。然后使用以下方法应用舍入: with localcontext() as ctx: ctx.prec = 5 # simplification for the sake of this example my_figure = +my_figure 只要我的数字不等于零,一切都很好。这根本不影响零,所以它的精度与以前一样(不是本例中的5) 有没有合适的方法可以做到这一点

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

with localcontext() as ctx:
    ctx.prec = 5 # simplification for the sake of this example
    my_figure = +my_figure
只要我的数字不等于零,一切都很好。这根本不影响零,所以它的精度与以前一样(不是本例中的5)


有没有合适的方法可以做到这一点,就像它也影响零一样?

做你想做的事吗?它不会保持5dp的精度,但至少它会将0E-30压缩到合理的程度。

my\u figure
是一个
float()
,而不是
Decimal()
localcontext()
不适用于浮点数,只适用于
decimal.decimal()
实例。
my\u figure=+my\u figure
应该做什么?(是指
abs(my_figure)
还是
my_figure+=my_figure
)?@MartijnPieters它是十进制的,很抱歉我不清楚。@JonClements'+'与-它应用精度和rounding@nirvanka每天学习一些新的东西-没有意识到可以这样做-谢谢
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