## 問題
你需要將數字格式化后輸出,并控制數字的位數、對齊、千位分隔符和其他的細節。
## 解決方案
格式化輸出單個數字的時候,可以使用內置的 `format()` 函數,比如:
~~~ python
>>> x = 1234.56789
>>> # Two decimal places of accuracy
>>> format(x, '0.2f')
'1234.57'
>>> # Right justified in 10 chars, one-digit accuracy
>>> format(x, '>10.1f')
' 1234.6'
>>> # Left justified
>>> format(x, '<10.1f')
'1234.6 '
>>> # Centered
>>> format(x, '^10.1f')
' 1234.6 '
>>> # Inclusion of thousands separator
>>> format(x, ',')
'1,234.56789'
>>> format(x, '0,.1f')
'1,234.6'
>>>
~~~
如果你想使用指數記法,將f改成e或者E(取決于指數輸出的大小寫形式)。比如:
~~~ python
>>> format(x, 'e')
'1.234568e+03'
>>> format(x, '0.2E')
'1.23E+03'
>>>
~~~
同時指定寬度和精度的一般形式是 `'[<>^]?width[,]?(.digits)?'` , 其中 `width` 和 `digits` 為整數,?代表可選部分。 同樣的格式也被用在字符串的 format() 方法中。比如:
~~~
>>> 'The value is {:0,.2f}'.format(x)
'The value is 1,234.57'
>>>
~~~
## 討論
數字格式化輸出通常是比較簡單的。上面演示的技術同時適用于浮點數和 `decimal` 模塊中的 `Decimal` 數字對象。
當指定數字的位數后,結果值會根據 `round()` 函數同樣的規則進行四舍五入后返回。比如:
~~~ python
>>> x
1234.56789
>>> format(x, '0.1f')
'1234.6'
>>> format(-x, '0.1f')
'-1234.6'
>>>
~~~
包含千位符的格式化跟本地化沒有關系。 如果你需要根據地區來顯示千位符,你需要自己去調查下 `locale` 模塊中的函數了。 你同樣也可以使用字符串的 `translate() `方法來交換千位符。比如:
~~~ python
>>> swap_separators = { ord('.'):',', ord(','):'.' }
>>> format(x, ',').translate(swap_separators)
'1.234,56789'
>>>
~~~
在很多Python代碼中會看到使用%來格式化數字的,比如:
~~~ python
>>> '%0.2f' % x
'1234.57'
>>> '%10.1f' % x
' 1234.6'
>>> '%-10.1f' % x
'1234.6 '
>>>
~~~
這種格式化方法也是可行的,不過比更加先進的 `format()` 要差一點。 比如,在使用%操作符格式化數字的時候,一些特性(添加千位符)并不能被支持。