简体   繁体   English

python中的两位有效数字如何取整?

[英]How to round down two significant figures in python?

I've seen the solutions around but they mostly round up to two significant figures and not down我已经看到了周围的解决方案,但它们大多四舍五入到两位有效数字而不是向下

I have tried these few methods我试过这几种方法

import math
v = 0.000129
math.floor(v*100)/100

-output-
0.0    

or或者

v = 0.000129
from decimal import Decimal
float(f"{Decimal(f'{v:.2g}'):f}")

-output-
0.00013

As you can see, I want to have two significant figures but do not want them rounded up.如您所见,我想要两个有效数字,但不希望它们四舍五入。 Decimal works to give the two sig figs but it rounds up while math just simply gives me 0. Decimal 可以给出两个 sig figs,但它四舍五入,而 math 只是简单地给了我 0。

ie a few to test即一些测试

1999 -> 1900
29901 - > 29000
0.0199 -> 0.019

Thanks!谢谢!

Mathematical solution without using any string conversion:不使用任何字符串转换的数学解决方案:

def round_down(n, sig_figs):
    import math
    return n - n % 10 ** math.ceil(math.log(abs(n), 10) - sig_figs)


>>> [round_down(n, 2) for n in [1990, 29901, 0.0199]]
[1900, 29000, 0.019]

Caveats:注意事项:

  • Doesn't work with input of 0不适用于输入0
  • Negative numbers are literally rounded in the negative direction, not towards zero (eg -0.0199-0.02 )负数实际上是朝负方向舍入,而不是朝零舍入(例如-0.0199-0.02

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM