Python小数格式

Python小数格式,第1张

Python小数格式

如果您拥有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 --> 11.2 --> 1.21.23 --> 1.231.234 --> 1.231.2345 --> 1.23

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

f-strings

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


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5673816.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-16
下一篇2022-12-16

发表评论

登录后才能评论

评论列表(0条)

    保存