1. Home
  2. Blog
  3. Software Development

Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl NumberFormat formats numbers for people: thousands separators, currencies, percentages, units and short forms like 1.2M, all in the reader’s locale. We ran it in Node.js 24 across six locales, found the non-breaking spaces that break string comparisons, a rounding difference from toFixed, and a 72x slowdown from creating formatters in a loop.

9 min read
Intl.NumberFormat in JavaScript: currency, compact, percent and units

Key takeaways

  • Intl NumberFormat takes a locale and options: new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(1234.5) gives 1.234,50 €.
  • Indian English groups digits as 12,34,567 and French uses a narrow no-break space, so never hard-code separators.
  • Intl rounded 1.005 to 1.01, while (1.005).toFixed(2) gave 1.00.
  • Creating a new formatter for each of 100,000 values took 3,770 ms; reusing one took 52 ms.

Showing 1234567.891 on a page is unfriendly in any language, and showing 1,234,567.89 to a German reader is actually wrong: they read the comma as a decimal point. Intl NumberFormat, part of JavaScript’s built-in internationalisation API, formats numbers correctly for any locale, with no library to install. It handles currencies, percentages, measurement units and compact forms such as “1.2M”.

All examples ran in Node.js v24.22.1 with ICU 78.3. Browsers support the same API; exact output can vary slightly between ICU versions, so test with the runtime your users have.

The basics

const nf = new Intl.NumberFormat("en-US");
nf.format(1234567.891)          // '1,234,567.891'
(1234567.891).toLocaleString("en-US")   // same result, one-off

Create a formatter with a locale tag (language plus optional region) and an options object, then call format. Leave the locale out, or pass undefined, to use the user’s own locale from the browser or system. Number.prototype.toLocaleString accepts the same arguments for one-off use.

The same number in six locales

Locale 1234567.891
en-US 1,234,567.891
en-IN 12,34,567.891
de-DE 1.234.567,891
fr-FR 1 234 567,891 (narrow no-break spaces)
ja-JP 1,234,567.891
ar-EG Arabic-Indic digits with Arabic separators

Separators, grouping and even digits change by locale. Indian English groups the first three digits, then pairs (lakhs and crores). Egyptian Arabic switched to Arabic-Indic digits by default; { numberingSystem: "latn" } forced Western digits and gave 1,234,567.891. Hindi in India (hi-IN) kept Western digits with Indian grouping.

Currency

const cur = (loc, c, v = 1234.5) =>
  new Intl.NumberFormat(loc, { style: "currency", currency: c }).format(v);

cur("en-US", "USD")              // '$1,234.50'
cur("de-DE", "EUR")              // '1.234,50 €'
cur("ja-JP", "JPY", 1500.6)      // '¥1,501'      no minor unit, rounded
cur("en-IN", "INR", 1234567.5)   // '₹12,34,567.50'
cur("en-US", "EUR")              // '€1,234.50'
cur("en-US", "BHD")              // 'BHD 1,234.500'  three decimals

The currency code (ISO 4217, such as USD, EUR, INR) decides the symbol and the number of decimals: yen has none, Bahraini dinar has three. The locale decides where the symbol goes and which separators to use, so euros look different for American and German readers. Always pass the currency explicitly; the locale never implies one.

{ currencyDisplay: "code" }        // 'USD 9.50'
{ currencyDisplay: "name" }        // '9.50 US dollars'
{ currencySign: "accounting" }     // -42 becomes '($42.00)'

The accounting style shows negative amounts in parentheses, as financial reports do. For rounding rules in stored money values, see our SQL ROUND guide; formatting should only ever happen for display. A user’s preferred currency or locale often arrives in the page address, so read it safely as shown in our URL query parameters guide.

Compact notation

const c = new Intl.NumberFormat("en-US", { notation: "compact" });
[999, 1234, 15300, 1234567, 2.5e9].map(v => c.format(v))
// [ '999', '1.2K', '15K', '1.2M', '2.5B' ]

{ notation: "compact", compactDisplay: "long" }   // en-US: '1.2 million'
en-IN compact                                     // '12L'   (lakh)
de-DE compact                                     // '1,2 Mio.'
ja-JP compact for 123456789                       // '1.2億'

Compact notation produces the short forms used on dashboards and social counters. It is locale-aware too: Indian English used lakhs, German “Mio.”, and Japanese counted in units of 100 million (億). Hand-written “K/M/B” helpers get all of these wrong.

Percent

const pct = new Intl.NumberFormat("en-US", { style: "percent" });
pct.format(0.485)    // '49%'
pct.format(48.5)     // '4,850%'   the classic mistake
new Intl.NumberFormat("en-US", { style: "percent", minimumFractionDigits: 1 }).format(0.485)  // '48.5%'
new Intl.NumberFormat("en-US", { style: "percent", signDisplay: "exceptZero" }).format(0.034) // '+3%'

Percent style multiplies by 100, so pass the ratio (0.485), not the already-multiplied value. By default it shows whole percents, rounding 48.5 up to 49; set fraction digits for precision. signDisplay: "exceptZero" adds a plus sign to growth figures.

Units

{ style: "unit", unit: "kilometer-per-hour" }                  // 88 → '88 km/h'
{ style: "unit", unit: "megabyte", unitDisplay: "long" }       // 512 → '512 megabytes'
de-DE { style: "unit", unit: "liter", unitDisplay: "long" }    // 2 → '2 Liter'

Unit style supports a defined set of simple units (length, mass, volume, duration, digital storage, temperature and more) and pairs joined with -per-. It localises the unit names and plurals but does not convert values: kilometres stay kilometres.

Digits and rounding

new Intl.NumberFormat("en-US", { maximumFractionDigits: 2 }).format(1.005)  // '1.01'
(1.005).toFixed(2)                                                         // '1.00'
{ maximumSignificantDigits: 3 }   // 123456 → '123,000'
{ minimumIntegerDigits: 3 }       // 7 → '007'
{ maximumFractionDigits: 0, roundingMode: "floor" }     // 2.9 → '2'
{ maximumFractionDigits: 0, roundingMode: "halfEven" }  // 2.5 → '2'
{ maximumFractionDigits: 0 }                            // 2.5 → '3'

The 1.005 result is worth remembering. The binary value stored for 1.005 is slightly below it, so toFixed rounded down to 1.00, while Intl rounded the shortest decimal representation and gave 1.01, which is what a human expects. The default rounding is “half expand” (2.5 becomes 3); newer engines also accept roundingMode values such as halfEven (banker’s rounding) and floor. Formatting 0.1 + 0.2 as currency gave a clean $0.30, hiding the floating-point error for display.

Scientific notation and very large numbers

{ notation: "scientific" }    // 123456 → '1.235E5'
{ notation: "engineering" }   // 123456 → '123.456E3'
{ useGrouping: false }        // 1234567 → '1234567'
format(12345678901234567890n) // '12,345,678,901,234,567,890'

format also accepts BigInt values and formats every digit exactly. useGrouping: false is useful for IDs, years and postcodes, which should never have separators.

formatToParts and formatRange

new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).formatToParts(1234.5)
// integer '1', group '.', integer '234', decimal ',', fraction '50', literal ' ', currency '€'

new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).formatRange(3, 5)
// '$3.00 – $5.00'

formatToParts returns the pieces with their types, so you can style the currency symbol or the decimals differently in HTML without parsing a formatted string. formatRange formats price ranges correctly for the locale, including the dash.

The non-breaking space trap

JSON.stringify(new Intl.NumberFormat("fr-FR").format(1234.5))   // '"1 234,5"' with U+202F
new Intl.NumberFormat("fr-FR").format(1234.5).includes(String.fromCharCode(0x202f)) // true
JSON.stringify(cur("de-DE", "EUR", 1))                           // '"1,00 €"' with U+00A0

The spaces in French numbers and before the euro sign are not ordinary spaces. They are a narrow no-break space (U+202F) and a no-break space (U+00A0), which stop a line break between the number and the symbol. They look identical on screen, so a test such as expect(price).toBe("1,00 €") typed with a normal space fails. Compare against the formatter’s own output, normalise with .replace(/\s/g, " "), or check parts. These characters also change between ICU versions, another reason not to hard-code formatted strings in tests or regular expressions.

Tip: never parse a formatted number back into a value. Keep the raw number in your data and format only at the moment of display.

Errors and locale support

new Intl.NumberFormat("en-US", { style: "currency" })
// TypeError: Currency code is required with currency style.

Intl.NumberFormat.supportedLocalesOf(["hi-IN", "xx-XX", "bn-BD"])   // [ 'hi-IN', 'bn-BD' ]
new Intl.NumberFormat("en-US").resolvedOptions().maximumFractionDigits   // 3

Missing required options throw immediately. Unsupported locales do not throw; they fall back to a supported one, so check supportedLocalesOf if it matters. resolvedOptions reveals the defaults actually in use, such as the 3 maximum fraction digits for plain decimals.

Performance: reuse your formatter

100,000 currency formats Time
New Intl.NumberFormat for every value 3,770 ms
toLocaleString with options for every value 3,652 ms
One formatter, reused 52 ms

Building a formatter loads locale data and resolves options, which is expensive. Creating one per value, or calling toLocaleString with options inside a loop, was about 72 times slower than creating it once and reusing it. In table rendering, create formatters at module level or cache them in a Map keyed by locale and options; our array methods guide shows mapping a list through one formatter.

Intl.NumberFormat cheat sheet

Goal Options
Thousands separators {}
Money { style: "currency", currency: "USD" }
Short counts { notation: "compact" }
Percent with one decimal { style: "percent", minimumFractionDigits: 1 }
Units { style: "unit", unit: "kilogram" }
Fixed decimals { minimumFractionDigits: 2, maximumFractionDigits: 2 }
No separators { useGrouping: false }
Show plus sign { signDisplay: "exceptZero" }

Final thoughts

Intl NumberFormat replaces every hand-written number formatter with one built-in, locale-aware tool. Pass the locale and the currency explicitly, give percent style a ratio, reuse formatters instead of creating them in loops, and never compare or parse formatted strings, because the spaces in them are not ordinary spaces. With those habits, the same code shows correct numbers to readers in Mumbai, Munich and Tokyo.

Frequently asked questions

How do I format a number as currency in JavaScript?

Create Intl.NumberFormat with a locale and the options style currency and a currency code such as USD, then call format with the number. The locale decides separators and symbol position.

How do I show 1.2K or 1.2M in JavaScript?

Use Intl.NumberFormat with notation set to compact. It produces short forms for each locale, such as 1.2M in English or 1,2 Mio. in German.

Why does my percent show 4,850 percent?

Percent style multiplies the value by 100. Pass the ratio, such as 0.485 for 48.5 percent, rather than a value that is already multiplied.

Why does my formatted number fail an equality test?

Many locales use no-break or narrow no-break spaces in formatted numbers. They look like spaces but are different characters, so compare with the formatter output or normalise the spaces first.

Is toLocaleString slower than Intl.NumberFormat?

Calling toLocaleString with options in a loop creates a new formatter each time. In our test that was about 72 times slower than creating one Intl.NumberFormat and reusing it.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

Confusion Matrix Explained: Precision, Recall, F1 and Thresholds in Python

Confusion matrix explained with Python: TP, FP, FN, TN, precision, recall, F1, the accuracy trap, threshold choice by cost and…

Read article →
Software Development

API Pagination: Offset vs Cursor vs Keyset, Tested on 1 Million Rows

API pagination explained: offset vs keyset and cursor pagination timed on 1 million rows, duplicates when data changes, the ties…

Read article →
DevOps

Git Submodule Explained: Add, Clone, Update and Remove Safely

Git submodule explained: add, clone, update –init, update –remote, the detached HEAD trap, foreach and clean removal, tested step by…

Read article →
Test Automation

Pytest tmp path Explained: tmp_path, tmp_path_factory and Temp Files

Pytest tmp_path explained: per-test temporary folders, tmp_path_factory for shared files, monkeypatch.chdir, legacy tmpdir, retention and basetemp.

Read article →
Software Testing

Test Case Prioritization: 6 Techniques Compared With APFD

Test case prioritization compared: risk, coverage, cost, history and random orders scored with APFD and time to find all faults…

Read article →
Databases & SQL

Full Text Search in SQL: FTS5, Ranking, Phrases and Speed

Full text search in SQL with SQLite FTS5: MATCH queries, phrases, prefixes, NEAR, stemming, BM25 ranking, snippets, two gotchas and…

Read article →
Databases & SQL

Generated Columns in SQL: Virtual vs Stored, Indexes and Limits

Generated columns in SQL explained: virtual vs stored, automatic updates, write errors, storage cost, indexing, JSON fields and support in…

Read article →
Software Development

Object Freeze in JavaScript: Shallow vs Deep, Seal and const

Object freeze in JavaScript explained: freeze vs seal vs const, strict mode errors, shallow vs deep freeze, frozen arrays, Map…

Read article →
Software Development

Python hashlib: SHA-256, File Hashes, HMAC and Password Hashing

Python hashlib explained: SHA-256 for strings and files, algorithm speeds, why passwords need PBKDF2 or scrypt, safe verification and HMAC…

Read article →
Software Development

Python UUID Explained: uuid1, uuid4, uuid5, uuid7 and Database Keys

Python UUID explained: uuid4, uuid5, uuid1 privacy, time-ordered uuid7, parsing, storage formats and UUIDs as database keys, tested on Python…

Read article →
Artificial Intelligence

Random Forest in Python: Bagging, Feature Sampling and OOB From Scratch

Random forest in Python from scratch: bootstrap sampling, feature sampling, number of trees, out-of-bag evaluation and impurity vs permutation importance.

Read article →
Software Development

MIME Types Explained: Content-Type, nosniff and a Common Types List

MIME types explained and tested in a browser: Content-Type, nosniff, scripts and stylesheets with wrong types, a common MIME types…

Read article →
DevOps

Git Clean Explained: Remove Untracked Files Without Regret

Git clean explained with dry runs: -n, -f, -d, -x, -X, exclusions, paths, nested repositories and interactive mode, plus a…

Read article →
Test Automation

Pytest approx: Comparing Floats With rel, abs and Collections

Pytest approx explained: default tolerances, the near-zero trap, rel and abs, lists and dicts, NaN, NumPy, and how it differs…

Read article →
Software Testing

Accessibility Testing: WCAG Checklist, Automated Tools and Manual Checks

Accessibility testing explained: WCAG basics, an axe-core scan of a broken and a fixed page, what automation missed, contrast checks…

Read article →
Databases & SQL

SQL UNPIVOT: Turn Columns Into Rows, 4 Ways Tested

SQL UNPIVOT explained: turn columns into rows with UNION ALL, CROSS JOIN with CASE, JSON functions or native UNPIVOT, with…

Read article →
Software Development

Intl NumberFormat in JavaScript: Currency, Compact, Percent and Units

Intl.NumberFormat in JavaScript: locales, currency, compact notation, percent, units, rounding, formatToParts, the non-breaking space trap and formatter reuse.

Read article →
Databases & SQL

SQL EXPLAIN Plan: How to Read Query Plans and Fix Slow Queries

SQL EXPLAIN plan explained: read scans, index searches, covering indexes and temporary sorts, with before and after timings for five…

Read article →
Artificial Intelligence

Decision Tree in Python: Gini, Entropy and Overfitting From Scratch

Decision tree in Python from scratch: Gini impurity, entropy, information gain, best splits, readable rules, and how depth and leaf…

Read article →
DevOps

Git Blame Explained: Find Who Changed a Line, and Why

Git blame explained with a real repository: ignore whitespace, line ranges and functions, ignore-revs files for formatting commits, moved code…

Read article →
Test Automation

Pytest Benchmark: Measure Speed and Catch Performance Regressions

Pytest benchmark tutorial: the benchmark fixture, reading results, parametrized and pedantic benchmarks, saving baselines and failing the build on regressions.

Read article →
Software Testing

Defect Density: Formula, Worked Examples and How to Use It

Defect density explained: the formula, a five-module worked example, per KLOC vs per function point, severity weighting, defect removal efficiency…

Read article →
Databases & SQL

Case Insensitive Search in SQL: LOWER, LIKE, COLLATE and Indexes

Case insensitive search in SQL: LOWER, LIKE, COLLATE NOCASE and expression indexes compared with query plans, plus accented letters and…

Read article →
Databases & SQL

ON DELETE CASCADE in SQL: CASCADE vs SET NULL vs RESTRICT

ON DELETE CASCADE in SQL tested: CASCADE vs SET NULL vs RESTRICT, multi-level cascades, the SQLite foreign key pragma, row…

Read article →
Artificial Intelligence

Logistic Regression in Python: Sigmoid, Log Loss and Gradient Descent From Scratch

Logistic regression in Python from scratch: sigmoid, log loss, gradient descent, odds ratios, thresholds, sigmoid overflow and separable data, tested…

Read article →
DevOps

Git Worktree Explained: Work on Two Branches at Once

Git worktree explained: add, list, remove, prune, lock and detached worktrees, a hotfix workflow, and the errors you will hit,…

Read article →
Test Automation

Pytest ini Explained: addopts, markers, testpaths and Precedence

Pytest ini explained: testpaths, addopts, strict markers, xfail_strict, filterwarnings, minversion, config file precedence and command-line overrides, tested.

Read article →
Software Testing

Test Estimation Techniques: WBS, Three Point PERT and Monte Carlo

Test estimation techniques worked through: WBS, three point PERT, total uncertainty, a Monte Carlo check, percentage rules and Wideband Delphi.

Read article →
Artificial Intelligence

Linear Regression in Python: Least Squares From Scratch, With R Squared

Linear regression in Python from scratch: closed form, NumPy least squares and gradient descent, R squared, RMSE, outliers and curved…

Read article →
DevOps

Git Remote Explained: Add, Set-URL, Rename, Remove and Push URLs

Git remote explained: add, set-url, separate push URLs, rename, remove and prune, plus how to avoid leaking tokens in remote…

Read article →
Test Automation

Pytest Mock: mocker.patch, spy, side_effect and autospec Explained

Pytest mock explained: mocker.patch, return_value, side_effect, spy, autospec and PropertyMock, with tested examples for APIs, clocks and retries.

Read article →
Software Testing

System Testing Explained: Types, Process and a Real End-to-End Example

System testing explained: types, entry and exit criteria, the process, and a real end-to-end test suite run against a small…

Read article →
Artificial Intelligence

Naive Bayes Classifier Explained: Build a Spam Filter in Python

Naive Bayes classifier explained by building a spam filter in Python: Bayes rule, the naive assumption, Laplace smoothing, log probabilities…

Read article →
DevOps

Git Branch Explained: Create, Switch, Rename, Delete and Recover

Git branch explained with tested commands: list, create, switch, rename, delete, merged checks, recovering deleted branches, remote tracking and naming.

Read article →
Test Automation

Pytest raises: Testing Exceptions, match and excinfo

Pytest raises explained with tested examples: match regexes, excinfo, custom and chained exceptions, parametrized error cases, pytest.warns and common mistakes.

Read article →
Software Testing

Non Functional Testing: Types, Metrics and a Real Load Test

Non functional testing explained: 10 key types, measurable requirements, latency percentiles and what a small real load test revealed about…

Read article →