Series: Numbers & Money lecture 5/6 (advanced). This one is for developers whose app shows prices, totals or quantities to people in more than one country, or reads numbers that people type into forms. By the end you will know which formatter to trust for each audience, which parsers turn 1,5 into fifteen without a word, and how to normalize user input so that a German, a Mexican and a Japanese user all get the number they meant.
If your US checkout shows $1,234.56 and you never tested anything else, this lecture is about the day a customer in Madrid types 1.234,56, or a user in Tokyo pastes 123 from a full-width IME. The earlier lectures dealt with what a number is (lecture 1: binary floating point, lecture 4: integer cents and Decimal). This one deals with the text on both sides of that number. Everything below was run on an Apple Silicon Mac (M1 Pro) with Python 3.9.6 (3.12.14 for comparison), PHP 8.5.6 with intl (ICU 78.3), the JavaScriptCore shell jsc that ships with macOS, Java 26, .NET 10.0.14 and Swift 6.4.2. Node.js and browsers were not run.
One number, many locales
A locale is a language plus regional conventions, written like en-US, es-MX or ja-JP. It decides the decimal mark, the grouping (thousands) separator, where the currency sign goes and how many fraction digits a currency has. Here is 1234567.891 through Intl.NumberFormat in jsc, plain and as currency:
const x = 1234567.891; for (const [l, c] of [["en-US","USD"],["es-ES","EUR"],["es-MX","MXN"],["ja-JP","JPY"],["ko-KR","KRW"],["en-IN","INR"]]) print(l, new Intl.NumberFormat(l).format(x), new Intl.NumberFormat(l, {style: "currency", currency: c}).format(x)); | Locale | Number | Currency |
|---|---|---|
| en-US | 1,234,567.891 | $1,234,567.89 |
| es-ES | 1.234.567,891 | 1.234.567,89 € |
| es-MX | 1,234,567.891 | $1,234,567.89 |
| es-AR | 1.234.567,891 | $ 1.234.567,89 |
| ja-JP | 1,234,567.891 | ¥1,234,568 |
| ko-KR | 1,234,567.891 | ₩1,234,568 |
| en-IN | 12,34,567.891 | ₹12,34,567.89 |
Things a hand-written toFixed(2) plus regex will get wrong: the euro sign goes after the number in Spain, with a no-break space (U+00A0) in front of it; French uses a narrow no-break space (U+202F) as the grouping separator; India groups by two digits after the first thousand; and yen and won have no minor unit, so the formatter rounded .891 away. PHP NumberFormatter, Java NumberFormat, .NET ToString("C", culture), Swift NumberFormatter and Python's locale.currency gave the same shapes for these locales.
The C library locale used by Python's locale module is a different data source from ICU. On this Mac, locale -a listed es_ES.UTF-8, es_MX.UTF-8, ja_JP.UTF-8 and ko_KR.UTF-8, so locale.format_string('%.2f', x, grouping=True) printed 1.234.567,89 for es_ES. On a slim Linux container those locales are often missing and setlocale raises locale.Error: unsupported locale setting, which is one reason servers usually format with ICU-based libraries instead.
Where the runtimes disagree
The same locale does not mean the same output. Three differences showed up in this run:
| Case | Output | Who printed it |
|---|---|---|
1234 in es-ES | 1234 | jsc Intl, Swift NumberFormatter |
1234 in es-ES | 1.234 | PHP intl, Java 26, .NET 10, Python es_ES locale |
| COP 1234567.891 | $ 1.234.567,89 | jsc, Java |
| COP 1234567.891 | $ 1.234.568 | PHP intl, .NET, Swift |
| yen sign | ¥ (U+00A5) | jsc, .NET, Swift |
| yen sign | ¥ (U+FFE5, full width) | PHP intl, Java, Python ja_JP |
| JPY 1234.5 | ¥1,235 | jsc (rounds half away from zero) |
| JPY 1234.5 | ¥1,234 / ¥1,234 | PHP, Python, Java, .NET (half to even) |
The first row is CLDR's "minimum grouping digits" rule for Spanish: a four-digit number gets no separator. jsc and Swift apply it; the others did not. All of them printed 12.345 for five digits. The rounding row links back to lecture 3: Intl's default rounding mode is half-expand, so ₩2.5 printed ₩3 in jsc and ₩2 in .NET.
The practical rule: never compare formatted strings across runtimes in tests, and never store a formatted string. Store the number; format at the edge. If you must assert on formatted output, pin the runtime and ICU version, or compare the parts (formatToParts in JS gave integer 12, group ., integer 345, decimal ,, fraction 6).
Compact numbers: 万, 億, 만, 억 and "mil"
Japanese and Korean group large numbers by 10,000, not by 1,000: 1 億 = 10^8, 1 万 = 10^4. A "compact" formatter is meant for this kind of display:
PHP DECIMAL_COMPACT_SHORT / jsc notation:"compact" en-US 12K | 1.2M | 123M | 1.2T ja-JP 1.2万 | 123万 | 1.2億 | 1.2兆 ko-KR 1.2만 | 123만 | 1.2억 | 1.2조 es-ES 12 mil | 1,2 M | 123 M | 1,2 B es-MX 12 k | 1.2 M | 123 M | 1.2 B (inputs: 12345, 1234567, 123456789, 1234567890123). PHP and jsc agreed exactly. Java 26's getCompactNumberInstance(SHORT) dropped the fraction (1万, 1億) and for es-MX printed 1235 k | 123457 k | 1234567890 k, which is not something you want on a dashboard. Swift's .notation(.compactName) printed 1.2億 and 1.2억. Note that Spanish "B" is a billón, 10^12, not the English billion.
Compact output is rounded, so it is for headlines, not for prices. For an exact Japanese or Korean amount such as 123,456,789 you write the grouping yourself:
def man_oku(n, units=("", "万", "億", "兆")): parts, i = [], 0 while n: n, r = divmod(n, 10000) if r: parts.append(f"{r}{units[i]}") i += 1 return "".join(reversed(parts)) or "0" print(man_oku(123456789), man_oku(100005000)) # 1億2345万6789 1億5000 ICU also has a spell-out mode: PHP NumberFormatter::SPELLOUT printed 一億二千三百四十五万六千七百八十九 for ja_JP and 일억 이천삼백사십오만 육천칠백팔십구 for ko_KR.
Parsing: "1,5" is fifteen in most parsers
Formatting mistakes look ugly. Parsing mistakes change the amount. We fed the same strings to every language's plain conversion function:
| Input | Python float | jsc parseFloat | jsc Number | PHP (float) | Java parseDouble | .NET TryParse (Number, Invariant) |
|---|---|---|---|---|---|---|
1,5 | ValueError | 1 | NaN | 1.0 | NumberFormatException | true, 15 |
1.234,56 | ValueError | 1.234 | NaN | 1.234 | NumberFormatException | false |
12abc | ValueError | 12 | NaN | 12.0 | NumberFormatException | false |
"" | ValueError | NaN | 0 | 0.0 | NumberFormatException | false |
123 | 123.0 | NaN | NaN | 0.0 | NumberFormatException | false |
1e3 | 1000.0 | 1000 | 1000 | 1000.0 | 1000.0 | false |
The quiet failures are the dangerous ones. parseFloat("1,5") is 1, not an error. PHP (float)"1.234,56" is 1.234. Number("") is 0, so an empty price field becomes free. And .NET with NumberStyles.Number allows thousands separators anywhere, so 1,5 parsed as fifteen; the plain double.Parse("1,5", InvariantCulture) did the same, and only NumberStyles.Float returned false. Java at least failed loudly: parseDouble("") threw NumberFormatException: empty String.
Locale-aware parsers are better but still surprising:
Java NumberFormat es-MX parse("1,5") -> 15 (pos 3 of 3) .NET TryParse es-MX "1,5" -> True 15 .NET double.Parse("1.5") with CurrentCulture = es-ES -> 15 Python locale.atof("1.5") under es_ES -> 15.0 Python locale.atof("12.34.56") under es_ES -> 123456.0 Java NumberFormat es-ES parse("1,234.56") -> 1.234 (pos 5 of 8) PHP NumberFormatter es_MX parse("1,5") -> false Python's locale.atof simply deletes every thousands separator, wherever it is, so a Spanish user who types 1.5 with a dot gets 15. Java's NumberFormat.parse stops at the first character it does not understand and reports the position, so parse("1,234.56") in es-ES returned 1.234 and left ,56… unless you check that the parse position reached the end of the string, you accept half a number.
Full-width and non-ASCII digits
Japanese IMEs produce full-width digits (123, U+FF11–FF13) when the user forgets to switch input mode, and Arabic-script locales use ٣ (U+0663). Languages treat them very differently:
| Call | Result |
|---|---|
Python int("123"), int("١٢٣"), int("१२३") | 123, 123, 123 |
Python int("²") although "²".isdigit() is True | ValueError: invalid literal for int() with base 10: '²' |
Java Integer.parseInt("123"), parseInt("٣") | 123, 3 |
Java Double.parseDouble("123") | NumberFormatException: For input string: "123" |
Java new BigDecimal("123") | 123 |
jsc parseInt("123"), Number("١٢٣") | NaN, NaN |
.NET int.Parse("١٢٣") | FormatException: The input string '١٢٣' was not in a correct format. |
Swift Int("123") / NumberFormatter es_ES | nil / 123 |
PHP (int)"123", is_numeric("123") | 0, false |
Python's acceptance looks friendly, but it means a validation regex like \d+ (which also matches any Unicode digit in Python 3) and int() let through digits your database or a downstream JavaScript service will reject. PHP's silent 0 is worse: a Japanese user who types 123 in a quantity field orders nothing, and no error is logged. Also note that str.isdigit() is the wrong check: it is True for ², which int() refuses. isdecimal() matched what int() accepts.
Common mistakes → what actually happens → fix
| Mistake | What we saw | Fix |
|---|---|---|
parseFloat(input) on a price field | "1,5" → 1, "12abc" → 12 | strict pattern first, then convert |
Number(input) and no empty check | "" → 0 | reject empty input explicitly |
double.Parse(s) with the server culture | es-ES culture: "1.5" → 15 | pass a culture; use NumberStyles.Float for machine data |
locale.atof for user input | es_ES: "1.5" → 15.0 | match a locale-specific pattern |
Java NumberFormat.parse(s) | "1,234.56" in es-ES → 1.234 | check ParsePosition reached s.length() |
PHP (int)$_POST['qty'] | "123" → 0, "12abc" → 12 | filter_var(..., FILTER_VALIDATE_INT) after NFKC |
| Comparing formatted strings in tests | 1234 vs 1.234 by runtime | compare numbers, or pin ICU |
| Creating a formatter per value | 15–66 times slower (below) | create once, reuse |
Safe input normalization
Decide the input locale (from the user's profile or the form, not from the server), normalize the text, match one strict pattern for that locale, and only then convert to Decimal or integer minor units (lecture 4):
import re, unicodedata from decimal import Decimal SEPS = {"es-ES": (".", ","), "es-MX": (",", "."), "en-US": (",", "."), "ja-JP": (",", "."), "ko-KR": (",", ".")} PAT = {k: re.compile(r"-?\d{1,3}(?:" + re.escape(g) + r"\d{3})*(?:" + re.escape(d) + r"\d+)?$|-?\d+(?:" + re.escape(d) + r"\d+)?$") for k, (g, d) in SEPS.items()} def parse_amount(text, loc): s = unicodedata.normalize("NFKC", text).strip() # 123 -> 123, full-width comma -> "," s = s.replace("−", "-").replace(" ", "").replace(" ", "").replace(" ", "") s = re.sub(r"^[¥¥₩$€]|[円원€]$", "", s) # one currency mark at either end if not s.isascii(): raise ValueError(f"non-ASCII digits: {text!r}") if not PAT[loc].match(s): raise ValueError(f"not a {loc} number: {text!r}") g, d = SEPS[loc] return Decimal(s.replace(g, "").replace(d, ".")) es-ES '1.234,56' -> Decimal('1234.56') es-ES '1,5' -> Decimal('1.5') es-ES '1.5' -> ValueError: not a es-ES number: '1.5' es-ES '€ 1.234,50' -> Decimal('1234.50') es-MX '1,5' -> ValueError: not a es-MX number: '1,5' ja-JP '1,234円' -> Decimal('1234') ja-JP '١٢٣' -> ValueError: non-ASCII digits: '١٢٣' ja-JP '1e3' -> ValueError: not a ja-JP number: '1e3' ko-KR '12,000원' -> Decimal('12000') ko-KR '−500' -> Decimal('-500') ko-KR '1,2,3' -> ValueError: not a ko-KR number: '1,2,3' The important result is the rejected rows. 1.5 typed in a Spanish form is ambiguous (a mistyped 1,5, or 1.500 missing digits?), so the safe answer is an error message, not a guess. NFKC (see the Unicode normalization lecture) folds full-width digits and the full-width comma, but it does not touch Arabic-Indic digits, so the isascii() check decides whether you accept those. For machine-to-machine data (JSON, CSV exports, APIs) do not use locales at all: use a dot decimal and no grouping, and parse with the invariant parser.
[[fig:num-fmt-pipeline]]
Measurement: what formatting costs
Formatting is rarely the bottleneck, until a report formats a column of 100,000 values. We formatted 100,000 random amounts (seed 42, 0 to 10,000,000.00, two decimals) in es-ES style, 5 runs, median, Apple Silicon Mac (M1 Pro):
[[fig:num-fmt-bench]]
| Method | ns per value |
|---|---|
PHP number_format($x, 2, ',', '.') | 211 |
Python 3.9 f"{x:,.2f}" (en style only) | 309 |
PHP NumberFormatter created once | 344 |
jsc Intl.NumberFormat created once | 357 |
PHP new NumberFormatter per value | 5,214 |
Python 3.9 locale.format_string es_ES | 7,137 |
jsc x.toLocaleString("es-ES", {...}) | 23,659 |
toLocaleString with options behaved as if it built a new formatter on every call: 66 times slower than reusing one Intl.NumberFormat. In PHP, constructing NumberFormatter inside the loop was 15 times slower than reusing it. Parsing showed the same pattern: Python float() took 77 ns, Decimal() 133 ns, our parse_amount 1,584 ns and locale.atof 2,135 ns per string (3.12.14: 51, 113, 1,103, 1,959). Strict parsing is about twenty times slower than float(), and still only 0.16 seconds for 100,000 form fields.
In production: a jackpot with no currency, and a zero that means "no winner"
Our other site shows Mexican lottery results in Spanish, built from the lottery's public CSV files. The jackpot column BOLSA holds whole pesos with no separators: 30300000 for the draw of 27 November 2026. On 29 November we checked all 4,297 Melate rows and all 1,689 Melate Retro rows. Every value was digits only. The job reads it like this:
"prize_1st": int(r["BOLSA"]) if (r.get("BOLSA") or "").strip().isdigit() else 0, and the page shows 0 as "Sin ganador (acumulado)", no winner, jackpot rolls over. That is a sensible meaning for a real zero; there are 173 of them, all in draws up to 2234. The trouble is the else 0. Feed it the same amount in any other format and it does not fail. It reports that nobody won:
'30300000' -> 30300000 '30,300,000' -> 0 (page: "Sin ganador") '30.300.000' -> 0 (page: "Sin ganador") '30300000.00' -> 0 (page: "Sin ganador") A parse failure becomes a statement of fact on a public page. If the agency ever adds thousands separators, the safer version raises or leaves the field empty, so the page can say the amount is unknown instead of saying something false.
The display side has its own locale question. The page formats the number with Python's "{:,}".format(value) and no currency: the live page showed Premio mayor 30,200,000. Here is the same amount through Intl.NumberFormat in jsc:
es-MX "30,200,000" currency MXN, 0 decimals: "$30,200,000" es-ES "30.200.000" currency MXN, 0 decimals: "30.200.000 MXN" en-US "30,200,000" currency MXN, 0 decimals: "MX$30,200,000" Commas happen to be right for Mexico, where these readers mostly are. A reader in Spain expects dots, and nobody can tell from the page that the amount is in pesos. We have not changed the page yet. The fix is to format with an explicit es-MX locale and MXN, rather than relying on Python's comma default.
One more thing came out of the data. The largest values are from April 1992: draw 455 shows 12000000000, twelve billion. Those amounts are almost certainly in old pesos. Mexico dropped three zeros on 1 January 1993, when 1,000 old pesos became 1 new peso. A number with no unit and no date is only half a value. If we ever chart the full history, those rows need converting or a note.
Honest limits / version notes
- Locale output comes from CLDR data inside ICU (PHP intl reported ICU 78.3), the JDK's own CLDR copy, Apple's Foundation, and the macOS C library. Versions change details like the es-ES four-digit rule and
a.m.-style spacing; we only checked the versions listed above. - jsc is JavaScriptCore on macOS. V8 (Node.js, Chrome) and SpiderMonkey use their own ICU builds and may differ in the "disagree" rows; not run here.
-
Intl.NumberFormatnotation: "compact"is from ECMA-402 (2020 edition);useGrouping: "always"(which printed1.234in es-ES) is newer and was checked only on this jsc. - The Java es-MX compact output is what Java 26 printed here; treat it as a reason to test compact formats per locale, not as documented behaviour.
- Python's
localedepends on the operating system's locale files.setlocalealso changes global process state, which is unsafe in threaded web servers.
Exercises
1. A Mexican user types 2,500 into a quantity field of your .NET app, which runs with CultureInfo.CurrentCulture set to es-ES. What does decimal.Parse(input) return, and what would decimal.Parse(input, CultureInfo.GetCultureInfo("es-MX")) return?
2. A Japanese form receives 1,200円 and 1.200. Using parse_amount(…, "ja-JP") above, what happens to each one?
Answers
1. Under es-ES the comma is the decimal mark, so decimal.Parse("2,500") returned 2.500, two and a half. With es-MX it returned 2500, because the comma is a grouping separator there (es-MX TryParse("1,5") even returned 15). The fix is to use the user's locale, not the server's.
2. 1,200円 is normalized by NFKC to 1,200円, the 円 is stripped and the result is Decimal('1200'). 1.200 matches the ja-JP pattern with a dot decimal, so it becomes Decimal('1.200'), one point two. If quantities are integers, use an integer-only pattern for that field, so the dot is rejected instead.
Continue
- Previous: Numbers & Money 4/6: money as integer cents and Decimal
- Next: Numbers & Money 6/6: summation error, NaN and -0.0
- Series start: 1/6: why 0.1 + 0.2 is not 0.3; rounding modes: 3/6
- Full-width input and string length: string length, emoji and graphemes
- Dates have the same locale problems: parsing and formatting dates
- CSV exports opened in Excel with a decimal comma: CSV encoding, BOM and Excel
- PHP type juggling basics: PHP types, strings and arrays
- All series: programming learning roadmap
Originally published at tlaboratory.net. Every output in this post was copied from a real terminal run.
