Python小数格式 [英] Python Decimals format

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

问题描述

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

WHat is a good way to format a python decimal like this way?

1.00->'1'

1.20->'1.2'

1.23->'1.23'

1.234->'1.23'

1.2345->'1.23'

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

推荐答案

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

If you have Python 2.6 or newer, use format:

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

对于Python 2.5或更早版本:

For Python 2.5 or older:

'%.3g'%(num)

说明:

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

{0}tells format to print the first argument -- in this case, num.

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

Everything after the colon (:) specifies the format_spec.

.3 将精度设置为3。

g 会删除不重要的零。参见
http://en.wikipedia.org/wiki/Printf#fprintf

g removes insignificant zeros. See 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字符串

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

这篇关于Python小数格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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