如何使Python格式的浮点数具有一定数量的有效数字? [英] How to make Python format floats with certain amount of significant digits?

查看:351
本文介绍了如何使Python格式的浮点数具有一定数量的有效数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的Python(2.4.3)输出数字具有某种格式.具体来说,如果该数字是一个终止的十进制数字,其中有效数字< = 6,则全部显示.但是,如果它的有效数字> 6,则仅输出6个有效数字.

I want my Python (2.4.3) output numbers to have a certain format. Specifically, if the number is a terminating decimal with <= 6 significant digits, show it all. However, if it has > 6 significant digits, then output only 6 significant digits.

"A"显示Python如何编写浮点数. "B"表示我希望他们如何写作.如何以这种方式使Python格式化我的数字?

"A" shows how Python is writing the floats. "B" shows how I want them written. How can I make Python format my numbers in that way?

A:
10188469102.605597
5.5657188485
3.539
22.1522612479
0
15.9638450858
0.284024
7.58096703786
24.3469152383

B:
1.01885e+10
5.56572
3.539
22.1523
0
15.9638
0.284024
7.58097
24.3469

推荐答案

您需要formatg修饰符,该修饰符会删除不重要的零;

You'll want the g modifier for format that drops insignificant zeroes;

>>> "{0:.6g}".format(5.5657188485)
'5.56572'
>>> "{0:.6g}".format(3.539)
'3.539'


对不起,我的更新还包含以下事实:我只能使用 Python 2.4.3,它没有format()函数.

Sorry, my update also includes the fact that I am restricted to using Python 2.4.3, which does not have format() function.

即使没有.format()功能,格式说明符也可以工作:

The format specifiers work even without the .format() function:

>>> for i in a:
...    print '%.6g' % (i,)
...
1.01885e+10
5.56572
3.539
22.1523
0
15.9638
0.284024
7.58097
24.3469

这篇关于如何使Python格式的浮点数具有一定数量的有效数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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