Number Format CLI with Intl
A Node CLI that formats a number for a given locale, supporting grouping, compact notation, and currency display via the Intl API.
Project
node-number-format-cli
Entry point: numfmt.mjs
Install
node --versionRun
node numfmt.mjs 1234567.891 en-US currency USDTest
node --test numfmt.test.mjsExpected output
Prints the number formatted per locale and options, for example $1,234,567.89 for US currency.Dependencies
- node >=20
What it does
Builds an Intl.NumberFormat from the locale and style arguments, choosing the right option set for plain, currency, compact, or percent output, and validates that the input is a finite number.
const [valueArg, locale = 'en-US', style = 'decimal', currency] = process.argv.slice(2);
const value = Number(valueArg);
if (!Number.isFinite(value)) { console.error('usage: numfmt <number> [locale] [decimal|currency|compact|percent] [code]'); process.exit(1); }
const options = { decimal: {}, currency: { style: 'currency', currency: currency ?? 'USD' }, compact: { notation: 'compact' }, percent: { style: 'percent' } }[style];
if (!options) { console.error('unknown style: ' + style); process.exit(1); }
console.log(new Intl.NumberFormat(locale, options).format(value));
Run and verify
node numfmt.mjs 1234567.891 en-US currency USD
Run the test command to check the implementation: node --test numfmt.test.mjs.
Expected Output
Formatting 1234567.891 as US currency rounds to cents and groups thousands:
$1,234,567.89
Limitations
Output depends on the ICU data bundled with the Node build; a small-icu build may fall back to a simplified locale, which changes the formatting.