Reference
API reference
Nine functions and one error class. Every one takes the locale as an argument, so data from Berlin, Mumbai and Cairo can sit side by side.
All functions take an optional locale: a BCP 47 tag ("pt-BR"), a list of tags, or nothing for the runtime default. Locale data is read from Intl.NumberFormat#formatToParts() once and cached. Pick a locale in the panel next to this page to see what it uses.
import {
parse,
tryParse,
parseCurrency,
detect,
parseColumn,
isValid,
createParser,
normalizeInput,
getLocaleInfo,
NumberParseError,
} from "numberparrot";parse#
parse(input, locale?, options?): number
Returns a number, or NaN when input is not a valid number for the locale. Numbers are returned unchanged. The locale is a BCP 47 tag ("pt-BR"), a list of tags, or nothing for the runtime default.
| Option | Type | Default | Description |
|---|---|---|---|
strict | boolean | false | Throw NumberParseError instead of returning NaN. Only the exact separators of the locale and recognized currencies are accepted, and a decimal separator needs digits on both sides. |
keepPercent | boolean | false | Return 15 for "15%" instead of 0.15. |
looseGrouping | boolean | false | Accept group separators anywhere ("1,23,4"). By default they must sit where thousands, or Indian lakh and crore, groups go. |
Besides the locale's own format, the default lenient mode accepts any whitespace (including U+00A0 and U+202F) or apostrophe as a group separator, the other one of . and , as a group separator, a leading (.5) or trailing (5.) decimal separator, signs and currency on either side, exponents (E, e, ×10^), ∞, and digits in any script.
import { parse } from "numberparrot";
parse("1.234,56", "pt-BR"); // 1234.56
parse("1'234.56", "de-CH"); // 1234.56
parse("12,34,567.89", "en-IN"); // 1234567.89
parse("(1.234,56)", "de-DE"); // -1234.56
parse("15%", "en-US"); // 0.15
parse("1.234,56", "en-US"); // NaN, not an en-US numbertryParse#
tryParse(input, locale?, options?): ParseResult
Takes the same arguments and options as parse and returns { ok, value, code, message }. When ok is false, value is NaN and code and message are the ones NumberParseError would carry, so a form can show a precise message without strict mode or try.
import { tryParse } from "numberparrot";
tryParse("1.234,56", "pt-BR");
// { ok: true, value: 1234.56, code: null, message: null }
tryParse("1,23", "en-US");
// { ok: false, value: NaN, code: "INVALID_GROUPING",
// message: "Group separators are in the wrong places" }parseCurrency#
parseCurrency(input, locale?, options?): CurrencyResult
Returns { amount, currency, symbol, fractionDigits }:
amount: the number, or integer minor units withtoMinorUnits.NaNwhen invalid.currency: the ISO 4217 code, ornullwhen none was found or recognized.symbol: the currency text as written (normalized), ornull.fractionDigits: minor unit digits of the currency (2 for USD, 0 for JPY, 3 for BHD), ornull.
| Option | Type | Default | Description |
|---|---|---|---|
toMinorUnits | boolean | false | Return an integer of minor units, computed on the decimal digits as text. |
currency | string | none | ISO code to assume when none is written. In strict mode a different currency throws CURRENCY_MISMATCH. |
strict | boolean | false | As in parse; unknown currencies throw UNKNOWN_CURRENCY and rounding throws PRECISION_LOSS. |
looseGrouping | boolean | false | As in parse. |
Symbols are resolved through Intl for the locale, so the same $ means USD in en-US, CAD in en-CA and MXN in es-MX.
import { parseCurrency } from "numberparrot";
parseCurrency("R$ 1.234,56", "pt-BR");
// { amount: 1234.56, currency: "BRL", symbol: "R$", fractionDigits: 2 }
parseCurrency("1 234,56 €", "fr-FR").currency; // "EUR"
parseCurrency("($1,234.56)", "en-US").amount; // -1234.56
parseCurrency("R$ 19,99", "pt-BR", { toMinorUnits: true }).amount; // 1999detect#
detect(input, candidates?): DetectResult
Guesses how a number string was written. candidates defaults to DEFAULT_CANDIDATES (23 common locales, en-US first); their order breaks ties.
| Field | Type | Description |
|---|---|---|
value | number | Best guess, NaN when the string is not a number in any convention. |
decimal | string | null | Decimal separator found or assumed. |
group | string | null | Group separator found or assumed. |
ambiguous | boolean | True when the string means two different numbers depending on the locale. |
confidence | number | 0 to 1. 1 means only one reading is possible, 0.5 means a coin flip. |
reason | string | Short English explanation. |
locales | string[] | Candidates that read the string as value, best match first. |
alternatives | number[] | Every distinct reading, value first. |
Switch the world board on the home page to Detect mode to see every reading of a string across 39 locales.
import { detect } from "numberparrot";
detect("1.234,56");
// { value: 1234.56, decimal: ",", group: ".", ambiguous: false, confidence: 0.95, ... }
detect("1,234");
// { value: 1234, ambiguous: true, confidence: 0.5, alternatives: [1234, 1.234], ... }parseColumn#
parseColumn(values, candidates?): ColumnResult
A single "1,234" is ambiguous, but a column rarely is. parseColumn runs detect on every cell, lets the unambiguous cells vote for the decimal separator, picks the first candidate locale that writes it and reads every cell with that one locale. candidates works as in detect.
| Field | Type | Description |
|---|---|---|
values | number[] | One number per cell. Blank cells and cells that do not fit are NaN. |
locale | string | null | The candidate used for every cell, null when no cell is a number. |
decimal | string | null | The decimal separator chosen for the column. |
ambiguous | boolean | True when no cell settles the format and the candidate order decided. |
confidence | number | 0 to 1. Lower when cells disagree or do not fit. |
reason | string | Short English explanation naming the deciding cell. |
invalid | number[] | Indexes of non blank cells that are not numbers in the chosen format. |
Paste a column into the box at the top of the home page to try it.
import { parseColumn } from "numberparrot";
parseColumn(["1,234", "12,5", "1.000,00"]);
// { values: [1.234, 12.5, 1000], locale: "pt-BR", decimal: ",",
// ambiguous: false, confidence: 0.93, invalid: [], reason: ... }
parseColumn(["1,5", "2,25", "3.75"]).invalid; // [2]: the odd one outisValid#
isValid(input, locale?, options?): boolean
true when parse would return a number. Never throws, even with strict: true.
import { isValid } from "numberparrot";
isValid("1.234,56", "pt-BR"); // true
isValid("1,23", "en-US"); // false, misplaced group
isValid("1,23", "en-US", { strict: true }); // false, no exceptioncreateParser#
createParser(locale?, options?): Parser
Resolves the locale once and returns { info, parse, tryParse, isValid, parseCurrency, normalizeInput } bound to it. The fastest way to parse many values, for example every row of a CSV file.
import { createParser } from "numberparrot";
const brl = createParser("pt-BR");
["1.234,56", "R$ 10,00", "(5,25)"].map(brl.parse); // [1234.56, 10, -5.25]
brl.info.decimal; // ","normalizeInput#
normalizeInput(value, locale?, options?): InputState
Returns { text, value, valid, complete } for a form field. text is the cleaned field text and complete is false while the user is still typing, for example right after a decimal separator. Options: maxFractionDigits (drop extra fraction digits) and allowNegative (default true).
import { normalizeInput } from "numberparrot";
normalizeInput("1.234,", "pt-BR");
// { text: "1.234,", value: 1234, valid: true, complete: false }
normalizeInput("١٢٫٥", "ar-EG");
// { text: "12٫5", value: 12.5, valid: true, complete: true }getLocaleInfo#
getLocaleInfo(locale?): LocaleInfo
Returns { locale, numberingSystem, decimal, group, minusSign, plusSign, percentSign, exponent, digits }, read from Intl.NumberFormat#formatToParts() once and cached. The locale picker on every docs page is built on it.
import { getLocaleInfo } from "numberparrot";
getLocaleInfo("de-CH");
// { locale: "de-CH", decimal: ".", group: "'", minusSign: "-",
// percentSign: "%", exponent: "E", digits: "0123456789", numberingSystem: "latn" }NumberParseError#
class NumberParseError extends Error
Thrown in strict mode. Has code, input and locale.
| Code | Meaning |
|---|---|
EMPTY | The input is empty or only whitespace. |
NOT_A_STRING | The input is not a string or a number. |
NO_DIGITS | The input contains no digits. |
INVALID_CHARACTER | An unexpected character appears inside the number. |
INVALID_SEPARATOR | A separator is not valid for the locale (strict mode) or appears twice in a row. |
MULTIPLE_DECIMALS | More than one decimal separator. |
MIXED_GROUPS | Two different group separators in one number. |
INVALID_GROUPING | Group separators in the wrong place, like 1,23 in en-US. |
INVALID_SIGN | Duplicated or conflicting signs or parentheses. |
INVALID_AFFIX | Text before or after the number that is not a sign, percent or currency. |
UNKNOWN_CURRENCY | Strict mode found a currency it cannot identify. |
CURRENCY_MISMATCH | The written currency differs from the currency option. |
PRECISION_LOSS | Converting to minor units would need rounding (strict mode). |
OUT_OF_RANGE | The value is not finite, or not a safe integer where one is required. |
import { parse, NumberParseError } from "numberparrot";
try {
parse("1,23", "en-US", { strict: true });
} catch (error) {
if (error instanceof NumberParseError) console.log(error.code); // "INVALID_GROUPING"
}Locales on the world board#
Every locale your runtime's Intl supports works, because nothing is hard coded. These are the 39 on the world board, as Node.js wrote them when this page was generated. The test suite covers 17 of them with hand written input and a round trip over more than 80 values.
| Locale | City | 1234567.89 | Decimal | Group | Digits |
|---|---|---|---|---|---|
en-US | New York | 1,234,567.89 | . | , | latn |
en-CA | Toronto | 1,234,567.89 | . | , | latn |
fr-CA | Montréal | 1 234 567,89 | , | no-break space | latn |
es-MX | Mexico City | 1,234,567.89 | . | , | latn |
pt-BR | São Paulo | 1.234.567,89 | , | . | latn |
es-AR | Buenos Aires | 1.234.567,89 | , | . | latn |
es-CO | Bogotá | 1.234.567,89 | , | . | latn |
es-CL | Santiago | 1.234.567,89 | , | . | latn |
en-GB | London | 1,234,567.89 | . | , | latn |
de-DE | Berlin | 1.234.567,89 | , | . | latn |
fr-FR | Paris | 1 234 567,89 | , | narrow no-break space | latn |
es-ES | Madrid | 1.234.567,89 | , | . | latn |
it-IT | Rome | 1.234.567,89 | , | . | latn |
nl-NL | Amsterdam | 1.234.567,89 | , | . | latn |
pt-PT | Lisbon | 1 234 567,89 | , | no-break space | latn |
de-CH | Zürich | 1'234'567.89 | . | apostrophe | latn |
sv-SE | Stockholm | 1 234 567,89 | , | no-break space | latn |
pl-PL | Warsaw | 1 234 567,89 | , | no-break space | latn |
cs-CZ | Prague | 1 234 567,89 | , | no-break space | latn |
uk-UA | Kyiv | 1 234 567,89 | , | no-break space | latn |
ru-RU | Moscow | 1 234 567,89 | , | no-break space | latn |
tr-TR | Istanbul | 1.234.567,89 | , | . | latn |
ar-EG | Cairo | ١٬٢٣٤٬٥٦٧٫٨٩ | ٫ | ٬ | arab |
ar-SA | Riyadh | ١٬٢٣٤٬٥٦٧٫٨٩ | ٫ | ٬ | arab |
fa-IR | Tehran | ۱٬۲۳۴٬۵۶۷٫۸۹ | ٫ | ٬ | arabext |
he-IL | Tel Aviv | 1,234,567.89 | . | , | latn |
sw-KE | Nairobi | 1,234,567.89 | . | , | latn |
en-ZA | Johannesburg | 1 234 567,89 | , | no-break space | latn |
en-IN | Mumbai | 12,34,567.89 | . | , | latn |
hi-IN | Delhi | 12,34,567.89 | . | , | latn |
bn-BD | Dhaka | ১২,৩৪,৫৬৭.৮৯ | . | , | beng |
ur-PK | Karachi | 1,234,567.89 | . | , | latn |
ja-JP | Tokyo | 1,234,567.89 | . | , | latn |
zh-CN | Shanghai | 1,234,567.89 | . | , | latn |
ko-KR | Seoul | 1,234,567.89 | . | , | latn |
th-TH | Bangkok | 1,234,567.89 | . | , | latn |
vi-VN | Hanoi | 1.234.567,89 | , | . | latn |
id-ID | Jakarta | 1.234.567,89 | , | . | latn |
en-AU | Sydney | 1,234,567.89 | . | , | latn |
Runtime support#
- Node.js 18 and newer, Deno, Bun and all modern browsers. Requires
Intl.NumberFormatwithformatToPartsand full ICU locale data, which Node ships by default since version 13. - The whole library is about 7 kB gzipped. Importing only
parsecosts about 3.6 kB. - ESM (
dist/index.js), CommonJS (dist/index.cjs) and type definitions for both.
Install#
npm install numberparrot