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.
Code
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:
localeships 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.