Python小数格式

发布于 2021-01-29 15:04:13

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

1.00 - > ‘1’
1.20 - > ‘1.2’
1.23 - > ‘1.23’
1.234 - > ‘1.23’
1.2345 - > ‘1.23’

关注者
0
被浏览
53
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    如果您拥有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'
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看