【问题标题】:How to format a floating number to fixed width in Python如何在 Python 中将浮点数格式化为固定宽度
【发布时间】:2012-02-11 17:28:09
【问题描述】:

如何将浮点数格式化为具有以下要求的固定宽度:

  1. 如果 n
  2. 添加尾随十进制零以填充固定宽度
  3. 截断超过固定宽度的十进制数字
  4. 对齐所有小数点

例如:

% formatter something like '{:06}'
numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]

for number in numbers:
    print formatter.format(number)

输出会是这样的

  23.2300
   0.1233
   1.0000
   4.2230
9887.2000

【问题讨论】:

    标签: python string numbers number-formatting


    【解决方案1】:
    numbers = [23.23, 0.1233, 1.0, 4.223, 9887.2]                                                                                                                                                   
                                                                                                                                                                                                    
    for x in numbers:                                                                                                                                                                               
        print("{:10.4f}".format(x)) 
    

    打印

       23.2300
        0.1233
        1.0000
        4.2230
     9887.2000
    

    花括号内的格式说明符遵循Python format string syntax。具体来说,在这种情况下,它由以下部分组成:

    • 冒号前的空字符串表示“将下一个提供的参数传递给format()”——在本例中,x 作为唯一参数。
    • 冒号后的10.4f 部分是format specification
    • f 表示定点表示法。
    • 10 是正在打印的字段的总宽度,左侧以空格填充。
    • 4 是小数点后的位数。

    【讨论】:

    • 所以我知道 4f 表示将小数限制为 4(尾随零),但是 10 是什么意思?这是否意味着这种格式不适用于大于 9999999999(十个 9)的整数?只是好奇。
    • 10.4 表示宽度为 10 个字符,精度为 4 位小数。
    • @hobbes3: 10 是最小字段宽度,即打印字符串的最小长度。默认情况下,数字右对齐并用空格填充 -- 详情请参阅 the documentation
    • 对于 2.7 之前的 Python:("%0.4f" % x).rjust(10)
    • @StevenRumbalski:或者只是"%10.4f" % x。在 Python 2.6 中,还可以使用"{0:10.4f}".format(x)
    【解决方案2】:

    这个问题已经有好几年了,但是从 Python 3.6 开始 (PEP498) 你可以使用新的f-strings

    numbers = [23.23, 0.123334987, 1, 4.223, 9887.2]
    
    for number in numbers:
        print(f'{number:9.4f}')
    

    打印:

      23.2300
       0.1233
       1.0000
       4.2230
    9887.2000
    

    【讨论】:

    • 注意宽度还包括点字符。因此,如果您指定 9 为宽度,则 1 将用于打印点,其他 8 将用于打印数字和空格。
    【解决方案3】:

    在 python3 中,以下工作:

    >>> v=10.4
    >>> print('% 6.2f' % v)
      10.40
    >>> print('% 12.1f' % v)
            10.4
    >>> print('%012.1f' % v)
    0000000010.4
    

    【讨论】:

    【解决方案4】:

    见 Python 3.x format string syntax:

    IDLE 3.5.1   
    numbers = ['23.23', '.1233', '1', '4.223', '9887.2']
    
    for x in numbers:  
        print('{0: >#016.4f}'. format(float(x)))  
    
         23.2300
          0.1233
          1.0000
          4.2230
       9887.2000
    

    【讨论】:

      【解决方案5】:

      您也可以用零填充。例如,如果您希望 number 的长度为 9 个字符,左填充零,请使用:

      print('{:09.3f}'.format(number))

      因此,如果number = 4.656,则输出为:00004.656

      对于您的示例,输出将如下所示:

      numbers  = [23.2300, 0.1233, 1.0000, 4.2230, 9887.2000]
      for x in numbers: 
          print('{:010.4f}'.format(x))
      

      打印:

      00023.2300
      00000.1233
      00001.0000
      00004.2230
      09887.2000
      

      当您想按字母顺序正确列出文件名时,这可能有用的一个示例。我注意到在一些linux系统中,数字是:1,10,11,..2,20,21,...

      因此,如果您想在文件名中强制执行必要的数字顺序,则需要在左侧填充适当数量的零。

      【讨论】:

        【解决方案6】:

        这将打印76.66:

        print("Number: ", f"{76.663254: .2f}")
        

        【讨论】:

          【解决方案7】:

          在 Python 3 中。

          GPA = 2.5
          print(" %6.1f " % GPA)
          

          6.1f 表示在点后显示 1 位数字,如果您在点后打印 2 位数字,则您应该只在 %6.2f 之后打印 %6.3f 3 位数字。

          【讨论】:

            【解决方案8】:

            我需要类似的东西来处理数组。这对我有帮助

            some_array_rounded=np.around(some_array, 5)
            

            【讨论】:

              【解决方案9】:

              我尝试了所有选项,例如

              1. pd.options.display.float_format = '{:.4f}'.format
              2. pd.set_option('display.float_format', str)
              3. pd.set_option('display.float_format', lambda x: f'%.{len(str(x%1))-2}f' % x)
              4. pd.set_option('display.float_format', lambda x: '%.3f' % x)

              但对我没有任何帮助。

              因此,在将变量/值 (var1) 分配给变量(例如 num1)时,我使用了 round(val,5) 之类的

              num1 = round(var1,5)
              

              这是一种粗略的方法,因为您必须在每个作业中使用此轮函数。但这可以确保您控制它的发生方式并得到您想要的。

              【讨论】:

                【解决方案10】:

                使用f-string literals

                >>> number = 12.34
                >>> print(f"{number}")
                12.34
                >>> print(f"{number:10f}")
                 12.340000
                >>> print(f"{number:10.4f}")
                   12.3400
                

                冒号:后面的10.4fformat specification,其中10是整数的字符宽度,第二个数字4是小数位数,f代表浮点数。

                也可以使用变量而不是硬编码宽度和小数位数:

                >>> number = 12.34
                >>> width = 10
                >>> decimals = 4
                >>> print(f"{number:{width}.{decimals}f}")
                   12.3400
                

                【讨论】:

                  猜你喜欢
                  • 2014-05-24
                  • 1970-01-01
                  • 2011-10-15
                  • 1970-01-01
                  • 2012-01-15
                  • 2015-03-28
                  • 2021-07-03
                  相关资源
                  最近更新 更多