簡體   English   中英

Python:如何格式化固定寬度的數字?

[英]Python: How do I format numbers for a fixed width?

讓我們說吧

numbers = [ 0.7653, 10.2, 100.2325, 500.9874 ]

我想通過改變小數位數來輸出具有固定寬度的數字,以獲得如下輸出:

0.7653
10.200
100.23
500.98

是否有捷徑可尋? 我一直在嘗試各種%f%d配置而沒有運氣。

結合兩個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

%運算符

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

或者,您可以使用切片

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

不幸的是,沒有解決這個問題的現成解決方案。 此外,具有字符串切片的解決方案不能充分地處理舍入和溢出。

因此,似乎必須編寫一個這樣的自己的函數:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM