如何在 Python 中将浮点数格式化为固定宽度

问题描述:

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

How do I format a floating number to a fixed width with the following requirements:

  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

for x in numbers:
    print "{:10.4f}".format(x)

印刷品

   23.2300
    0.1233
    1.0000
    4.2230
 9887.2000

花括号内的格式说明符遵循 Python 格式字符串语法.具体来说,在这种情况下,它由以下部分组成:

The format specifier inside the curly braces follows the Python format string syntax. Specifically, in this case, it consists of the following parts:

  • 冒号前的 空字符串 表示将下一个提供的参数带到 format()"——在这种情况下,x 作为唯一的论点.
  • 冒号后的 10.4f 部分是 格式规范.
  • f 表示定点符号.
  • 10 是要打印的字段的总宽度,由空格填充.
  • 4 是小数点后的位数.
  • The empty string before the colon means "take the next provided argument to format()" – in this case the x as the only argument.
  • The 10.4f part after the colon is the format specification.
  • The f denotes fixed-point notation.
  • The 10 is the total width of the field being printed, lefted-padded by spaces.
  • The 4 is the number of digits after the decimal point.