【问题标题】:Python: How do I format numbers for a fixed width?Python:如何格式化固定宽度的数字?
【发布时间】:2014-07-25 16:22:52
【问题描述】:

我们说

numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]

我想通过改变小数位数来输出具有固定宽度的数字以获得如下输出:

0.7653
10.200
100.23
500.98

有没有简单的方法来做到这一点?我一直在尝试各种 %f%d 配置,但没有成功。

【问题讨论】:

  • 最后一轮不应该到500.99吗?

标签: python string numbers fixed-width


【解决方案1】:

结合两个str.format / format 调用:

numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]
>>> for n in numbers:
...     print('{:.6s}'.format('{:0.4f}'.format(n)))
...     #  OR format(format(n, '0.4f'), '.6s')
...
0.7653
10.200
100.23
500.98

% operators:

>>> for n in numbers:
...     print('%.6s' % ('%.4f' % n))
...
0.7653
10.200
100.23
500.98

或者,您可以使用slicing

>>> for n in numbers:
...     print(('%.4f' % n)[:6])
...
0.7653
10.200
100.23
500.98

【讨论】:

  • 谢谢!正是我需要的。
  • 请注意,这些解决方案不会四舍五入最后的小数。
【解决方案2】:

很遗憾,对于这个问题没有现成的解决方案。此外,字符串切片的解决方案不能充分处理舍入和溢出问题。

因此,似乎必须像这样编写自己的函数:

def to_fixed_width(n, max_width, allow_overflow = True, do_round = True):
    if do_round:
        for i in range(max_width - 2, -1, -1):
            str0 = '{:.{}f}'.format(n, i)
            if len(str0) <= max_width:
                break
    else:
        str0 = '{:.42f}'.format(n)
        int_part_len = str0.index('.')
        if int_part_len <= max_width - 2:
            str0 = str0[:max_width]
        else:
            str0 = str0[:int_part_len]
    if (not allow_overflow) and (len(str0) > max_width):
        raise OverflowError("Impossible to represent in fixed-width non-scientific format")
    return str0

结果行为:

>>> to_fixed_width(0.7653, 6)
'0.7653'
>>> to_fixed_width(10.2, 6)
'10.200'
>>> to_fixed_width(100.2325, 6)
'100.23'
>>> to_fixed_width(500.9874, 6)
'500.99'
>>> to_fixed_width(500.9874, 6, do_round = False)
'500.98'

更多示例:

>>> to_fixed_width(-0.3, 6)
'-0.300'
>>> to_fixed_width(0.000001, 6)
'0.0000'
>>> to_fixed_width(999.99, 6)
'999.99'
>>> to_fixed_width(999.999, 6)
'1000.0'
>>> to_fixed_width(1000.4499, 6)
'1000.4'
>>> to_fixed_width(1000.4499, 6, do_round = False)
'1000.4'
>>> to_fixed_width(12345.6, 6)
'12346'
>>> to_fixed_width(1234567, 6)
'1234567'
>>> to_fixed_width(1234567, 6, allow_overflow = False)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 15, in to_fixed_width
OverflowError: Impossible to represent in fixed-width non-scientific format
>>> to_fixed_width(float('nan'), 6)
'nan'

【讨论】:

  • 这是一个了不起的通用功能,感谢@Roman!我只需要这个案例(allow_overflow=False,do_round=True),所以我使用了你的函数的修改版本。
猜你喜欢
  • 2011-10-15
  • 2012-01-15
  • 2012-02-11
  • 1970-01-01
  • 2014-05-24
  • 2018-01-28
  • 1970-01-01
相关资源
最近更新 更多