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

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

问题描述

我需要四舍五入才能在UI中显示.例如,达到一个重要的数字:

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

1234-> 1000

1234 -> 1000

0.12-> 0.1

0.12 -> 0.1

0.012-> 0.01

0.012 -> 0.01

0.062-> 0.06

0.062 -> 0.06

6253-> 6000

6253 -> 6000

1999-> 2000

1999 -> 2000

是否有使用Python库执行此操作的好方法,还是我必须自己编写它?

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

如果浮点数大于1,则可能需要将其转换为整数.

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

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

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