【问题标题】:In python, i want to thousands separate decimal numbers and display with exactly 2 decimal digits在 python 中,我想要数千个单独的十进制数字并以 2 个十进制数字显示
【发布时间】:2019-05-18 00:23:59
【问题描述】:

考虑以下数字:

1000.10
1000.11
1000.113

我想让这些在 python 中打印出来:

1,000.10
1,000.11
1,000.11

以下转换几乎可以做到这一点,除了当小数点右侧的第二个数字为零时,零会被省略,因此数字无法正确排列。

这是我的尝试:

for n in [1000.10, 1000.11, 1000.112]:
    nf = '%.2f' %n   # nf is a 2 digit decimal number, but a string
    nff = float(nf)  # nff is a float which the next transformation needs 
    n_comma = f'{nff:,}' # this puts the commas in 
    print('%10s' %n_comma)

 1,000.1
1,000.11
1,000.11

有没有办法避免在第一个数字中省略结尾的零?

【问题讨论】:

    标签: python floating-point type-conversion


    【解决方案1】:

    您需要格式说明符',.2f'。如您所述,, 执行逗号分隔千位,而.2f 指定保留两位数:

    print([f'{number:,.2f}' for number in n])
    

    输出:

    ['1,000.10', '1,000.11', '1,000.11']
    

    【讨论】:

      【解决方案2】:

      您可以简单地使用 f'{n:,.2f}' 来组合因此和分隔符和 2 个十进制数字格式说明符:

      for n in [1000.10, 1000.11, 1000.112]:
          print(f'{n:,.2f}')
      

      输出

      1,000.10
      1,000.11
      1,000.11
      

      【讨论】:

        【解决方案3】:

        你可以这样做:

        num = 100.0
        print(str(num) + "0")
        

        因此,您将数字打印为字符串加上末尾的 0。 更新: 所以它不会对所有数字都这样做,请尝试执行以下操作:

        if num == 1000.10:
        #add the zero
        elif num == 1000.20:
        #again, add the zero
        #and so on and so on...
        

        因此,如果数字末尾有零(其十进制值为 0.10、0.20、0.30 等),则加一,如果没有,则不要。

        【讨论】:

        • 这肯定行得通,但不如使用上面建议的格式说明符',.2f'那么优雅。
        猜你喜欢
        • 2018-03-20
        • 1970-01-01
        • 2012-05-11
        • 1970-01-01
        • 2020-08-27
        • 1970-01-01
        • 2013-06-09
        • 2016-12-18
        相关资源
        最近更新 更多