23

32757121.33として表示されるように10進数をフォーマットするにはどうすればよい32.757.121,33ですか?

4

4 に答える 4

26

使用locale.format()

>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'German')
'German_Germany.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32.757.121,33

ロケールの変更を数値の表示に制限し(などを使用する場合locale.format()locale.str()、他のロケール設定は影響を受けないままにすることができます。

>>> locale.setlocale(locale.LC_NUMERIC, 'English')
'English_United States.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32,757,121.33
>>> locale.setlocale(locale.LC_NUMERIC, 'German')
'German_Germany.1252'
>>> print(locale.format('%.2f', 32757121.33, True))
32.757.121,33
于 2012-10-26T07:31:47.690 に答える
17

私は別の解決策を見つけました:

'{:,.2f}'.format(num).replace(".","%").replace(",",".").replace("%",",")
于 2012-10-26T16:02:37.537 に答える
8

locale何らかの理由で使用できない、または使用したくない場合は、正規表現を使用して使用することもできます。

import re
def sep(s, thou=",", dec="."):
    integer, decimal = s.split(".")
    integer = re.sub(r"\B(?=(?:\d{3})+$)", thou, integer)
    return integer + dec + decimal

sep()標準のPythonfloatの文字列表現を受け取り、カスタムの千と小数点を使用して返します。

>>> s = "%.2f" % 32757121.33
>>> sep(s)
'32,757,121.33'
>>> sep(s, thou=".", dec=",")
'32.757.121,33'

説明:

\B      # Assert that we're not at the start of the number
(?=     # Match at a position where it's possible to match...
 (?:    #  the following regex:
  \d{3} #   3 digits
 )+     #  repeated at least once
 $      #  until the end of the string
)       # (thereby ensuring a number of digits divisible by 3
于 2012-10-26T14:49:06.560 に答える
0
>>> import locale

>>> locale.setlocale(locale.LC_ALL, 'en_GB.UTF-8')
'en_GB.UTF-8'
>>> print(locale.format_string('%.2f', 12742126.15, True))
12,742,126.15

このサンプルコードは、DockerコンテナのGBで機能します。

FROM python:3.8.2-slim-buster

RUN apt-get update && apt-get install -y locales && \
    sed -i -e 's/# en_GB.UTF-8 UTF-8/en_GB.UTF-8 UTF-8/' /etc/locale.gen && \
    dpkg-reconfigure --frontend=noninteractive locales

ENV LANG en_GB.UTF-8
ENV LC_ALL en_GB.UTF-8

ロケールは、端末(Linux Dirstro)で次のコマンドを実行することで見つけることができます。

locale -a

次に、ロケールの完全なリストが表示されます。

en_AG.utf8
en_AU.utf8
...
en_GB.utf8
...
于 2021-12-07T16:12:56.060 に答える