Locale Formats Currency For You

Render grouped currency and number strings with locale.currency and locale.format_string so separators come from the locale database, not string surgery.

PythonConfig Management

Code

pythonsnippet
13 lines
import locale

# locale.setlocale 不带 category 参数时只设 LC_CTYPE:
# 货币/数字格式化必须显式传 LC_MONETARY / LC_ALL
locale.setlocale(locale.LC_ALL, "")

amount = 1234567.891
print("currency :", locale.currency(amount, grouping=True))
print("number   :", locale.format_string("%.2f", amount, grouping=True))

# localeconv 暴露当前区域的符号与分组规则,调试格式差异用
conv = locale.localeconv()
print("symbol   :", conv["currency_symbol"], "| grouping:", conv["mon_grouping"])

Output

Captured from a sandboxed run of this snippet in the build pipeline.

currency : ¥1,234,567.89
number   : 1,234,567.89
symbol   : ¥ | grouping: [3, 0]

The structure in motion

Module-level bindings hold the data — amount, conv — with no function scope in between.

Caveats

  • Nothing to install: locale ships with the Python standard library.

Putting it to use

Running the file prints labeled results such as currency :, number :, symbol : — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `locale`. Its state lives in module-level bindings: `amount`, `conv`.