2013-10-06 64 views
0

如何在python 2.7中將十進制數123456.789格式化爲123.456,78而不使用區域設置?在Python 2.7中使用DOT作爲千分隔符

千位分隔符應該是DOT而不是COMMA,小數點分隔符應該是COMMA而不是DOT。

有什麼快速的方法來轉換?

+0

爲什麼要避免'locale'? – Marcin

回答

2

如果你真的想避免locale,那麼你可以從format(val, ',')返回的值工作,然後交換,.

>>> a = 1234567.89 
>>> from string import maketrans 
>>> trans = maketrans('.,', ',.') 
>>> format(a, ',.2f').translate(trans) 
'1.234.567,89' 
1

的一種方法是改變你的locale

>>> import locale 
>>> locale.setlocale(locale.LC_ALL, 'deu_DEU') 
'German_Germany.1252' 
>>> "{0:n}".format(12345.67) 
'12.345,7' 
>>> locale.setlocale(locale.LC_ALL, '') 
'English_United Kingdom.1252' 
>>> "{0:n}".format(12345.67) 
'12,345.7' 
>>>