Python小数格式


73

WHat是像这样格式化python十进制的好方法吗?

1.00 - > '1'
1.20 - > '1.2'
1.23 - > '1.23'
1.234 - > '1.23'
1.2345 - > '1.23'


1
如果您使用的是Decimal而不是float,那么您可能还需要查看stackoverflow.com/questions/11227620/…{:g}不会从小数点中删去无关紧要的零。
Pankrat

Answers:


118

如果您拥有Python 2.6或更高版本,请使用format

'{0:.3g}'.format(num)

对于Python 2.5或更早版本:

'%.3g'%(num)

说明:

{0}告诉format打印第一个参数-在这种情况下,num

冒号(:)之后的所有内容均指定format_spec

.3 将精度设置为3。

g删除无关紧要的零。请参阅 http://en.wikipedia.org/wiki/Printf#fprintf

例如:

tests=[(1.00, '1'),
       (1.2, '1.2'),
       (1.23, '1.23'),
       (1.234, '1.23'),
       (1.2345, '1.23')]

for num, answer in tests:
    result = '{0:.3g}'.format(num)
    if result != answer:
        print('Error: {0} --> {1} != {2}'.format(num, result, answer))
        exit()
    else:
        print('{0} --> {1}'.format(num,result))

产量

1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23

使用Python 3.6或更高版本,您可以使用f-strings

In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'

17
看来这会导致Python 2.7进入大数的科学表示法:>>>“ {0:.3g}”。format(100.20)'100'>>>“ {0:.3g}”。format(1001.20 ) '1E + 03'
vdboor

4
那么如何设置no Exponent notation。作为{:,2f}.format(number)剂量,但也删除了不重要的零点
艾尔温湖

1
@unutbu-知道如何使'{0:.3g}'适用于Python fStrings吗?
Scott Skiles

1
@ScottSkiles:num=1.2345; f'{num:.3g}'返回'1.23'。请参阅此代码等效性说明。
unutbu

太棒了!值得编辑此答案吗?我在SO的其他地方找到了这个。
Scott Skiles

25

贾斯汀的答案只有第一部分是正确的。使用“%.3g”不适用于所有情况,因为.3不是精度,而是总位数。尝试使用1000.123之类的数字,它会中断。

因此,我会使用贾斯汀的建议:

>>> ('%.4f' % 12340.123456).rstrip('0').rstrip('.')
'12340.1235'
>>> ('%.4f' % -400).rstrip('0').rstrip('.')
'-400'
>>> ('%.4f' % 0).rstrip('0').rstrip('.')
'0'
>>> ('%.4f' % .1).rstrip('0').rstrip('.')
'0.1'

14

这是一个可以解决问题的函数:

def myformat(x):
    return ('%.2f' % x).rstrip('0').rstrip('.')

这是您的示例:

>>> myformat(1.00)
'1'
>>> myformat(1.20)
'1.2'
>>> myformat(1.23)
'1.23'
>>> myformat(1.234)
'1.23'
>>> myformat(1.2345)
'1.23'

编辑:

通过查看其他人的答案和实验,我发现g为您完成了所有剥离工作。所以,

'%.3g' % x

的功能也非常出色,并且与其他人的建议略有不同(使用'{0:.3}'。format()东西)。我猜你选。


真好 比我的清洁得多。
Mike Cialowicz

4
当您得到0.0000005之类的信息时,尽管我相信'%.3g'%x将开始为您提供指数?
昂贵的2012年

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.