您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python小数格式

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 --> 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'
python 2022/1/1 18:26:20 有421人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶