如何在Python中按有效数字进行四舍五入
我需要把一个浮点数四舍五入,以便在用户界面上显示。例如,要保留一位有效数字:
1234 -> 1000
0.12 -> 0.1
0.012 -> 0.01
0.062 -> 0.06
6253 -> 6000
1999 -> 2000
有没有简单的方法可以使用Python库来做到这一点,还是我必须自己写代码?
27 个回答
89
f'{float(f"{i:.1g}"):g}'
# Or with Python <3.6,
'{:g}'.format(float('{:.1g}'.format(i)))
这个解决方案和其他的都不一样,因为:
- 它准确地解决了提问者的问题
- 它不需要任何额外的包
- 它不需要任何用户自定义的辅助函数或数学运算
对于任意数量的有效数字n
,你可以使用:
print('{:g}'.format(float('{:.{p}g}'.format(i, p=n))))
测试:
a = [1234, 0.12, 0.012, 0.062, 6253, 1999, -3.14, 0., -48.01, 0.75]
b = ['{:g}'.format(float('{:.1g}'.format(i))) for i in a]
# b == ['1000', '0.1', '0.01', '0.06', '6000', '2000', '-3', '0', '-50', '0.8']
注意:使用这个解决方案时,无法根据输入动态调整有效数字的数量,因为没有标准的方法来区分不同尾随零的数字(比如3.14 == 3.1400
)。如果你需要这样做,就需要使用像to-precision包中提供的非标准函数。
134
%g 在字符串格式化中会将浮点数格式化为一定数量的有效数字。它有时会使用科学计数法(比如用'e'表示),所以在将格式化后的字符串转换回浮点数时,可以通过 %s 的字符串格式化来实现。
>>> '%s' % float('%.1g' % 1234)
'1000'
>>> '%s' % float('%.1g' % 0.12)
'0.1'
>>> '%s' % float('%.1g' % 0.012)
'0.01'
>>> '%s' % float('%.1g' % 0.062)
'0.06'
>>> '%s' % float('%.1g' % 6253)
'6000.0'
>>> '%s' % float('%.1g' % 1999)
'2000.0'
203
你可以用负数来对整数进行四舍五入:
>>> round(1234, -3)
1000.0
所以如果你只需要最重要的数字:
>>> from math import log10, floor
>>> def round_to_1(x):
... return round(x, -int(floor(log10(abs(x)))))
...
>>> round_to_1(0.0232)
0.02
>>> round_to_1(1234243)
1000000.0
>>> round_to_1(13)
10.0
>>> round_to_1(4)
4.0
>>> round_to_1(19)
20.0
如果这个数字大于1,你可能需要把浮点数转换成整数。