gpt4 book ai didi

python - 如何在 Python 中将数字舍入为有效数字

转载 作者:IT老高 更新时间:2023-10-28 12:35:05 25 4
gpt4 key购买 nike

我需要对 float 进行舍入以显示在 UI 中。例如,一个有效数字:

1234 -> 1000

0.12 -> 0.1

0.012 -> 0.01

0.062 -> 0.06

6253 -> 6000

1999 -> 2000

有没有使用 Python 库的好方法,还是我必须自己编写?

最佳答案

您可以使用负数来舍入整数:

>>> 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

如果 float 大于 1,您可能需要注意将 float 转换为整数。

关于python - 如何在 Python 中将数字舍入为有效数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3410976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com