如何在 Python 中将数字四舍五入为有效数字 [英] How to round a number to significant figures in Python

查看:18
本文介绍了如何在 Python 中将数字四舍五入为有效数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要舍入要在 UI 中显示的浮点数.例如,到一位有效数字:

1234 ->10000.12 ->0.10.012 ->0.010.062 ->0.066253 ->60001999 ->2000年

是否有使用 Python 库的好方法,或者我必须自己编写?

解决方案

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

<预><代码>>>>回合(1234,-3)1000.0

因此,如果您只需要最高有效数字:

<预><代码>>>>从数学导入 log10,地板>>>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,您可能需要注意将浮点数转换为整数.

I need to round a float to be displayed in a UI. e.g, to one significant figure:

1234 -> 1000

0.12 -> 0.1

0.012 -> 0.01

0.062 -> 0.06

6253 -> 6000

1999 -> 2000

Is there a nice way to do this using the Python library, or do I have to write it myself?

解决方案

You can use negative numbers to round integers:

>>> round(1234, -3)
1000.0

Thus if you need only most significant digit:

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

You'll probably have to take care of turning float to integer if it's bigger than 1.

这篇关于如何在 Python 中将数字四舍五入为有效数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆