numberparrot v1.1.0

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.

7 min readUpdated numberparrot 1.1.0

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.

imports.ts
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.

OptionTypeDefaultDescription
strictbooleanfalseThrow 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.
keepPercentbooleanfalseReturn 15 for "15%" instead of 0.15.
looseGroupingbooleanfalseAccept 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.

parse.ts
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 number

tryParse#

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.

tryParse.ts
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 with toMinorUnits. NaN when invalid.
  • currency: the ISO 4217 code, or null when none was found or recognized.
  • symbol: the currency text as written (normalized), or null.
  • fractionDigits: minor unit digits of the currency (2 for USD, 0 for JPY, 3 for BHD), or null.
OptionTypeDefaultDescription
toMinorUnitsbooleanfalseReturn an integer of minor units, computed on the decimal digits as text.
currencystringnoneISO code to assume when none is written. In strict mode a different currency throws CURRENCY_MISMATCH.
strictbooleanfalseAs in parse; unknown currencies throw UNKNOWN_CURRENCY and rounding throws PRECISION_LOSS.
looseGroupingbooleanfalseAs 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.

parseCurrency.ts
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; // 1999

detect#

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.

FieldTypeDescription
valuenumberBest guess, NaN when the string is not a number in any convention.
decimalstring | nullDecimal separator found or assumed.
groupstring | nullGroup separator found or assumed.
ambiguousbooleanTrue when the string means two different numbers depending on the locale.
confidencenumber0 to 1. 1 means only one reading is possible, 0.5 means a coin flip.
reasonstringShort English explanation.
localesstring[]Candidates that read the string as value, best match first.
alternativesnumber[]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.

detect.ts
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.

FieldTypeDescription
valuesnumber[]One number per cell. Blank cells and cells that do not fit are NaN.
localestring | nullThe candidate used for every cell, null when no cell is a number.
decimalstring | nullThe decimal separator chosen for the column.
ambiguousbooleanTrue when no cell settles the format and the candidate order decided.
confidencenumber0 to 1. Lower when cells disagree or do not fit.
reasonstringShort English explanation naming the deciding cell.
invalidnumber[]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.

parseColumn.ts
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 out

isValid#

isValid(input, locale?, options?): boolean

true when parse would return a number. Never throws, even with strict: true.

isValid.ts
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 exception

createParser#

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.

createParser.ts
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).

normalizeInput.ts
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.

getLocaleInfo.ts
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.

CodeMeaning
EMPTYThe input is empty or only whitespace.
NOT_A_STRINGThe input is not a string or a number.
NO_DIGITSThe input contains no digits.
INVALID_CHARACTERAn unexpected character appears inside the number.
INVALID_SEPARATORA separator is not valid for the locale (strict mode) or appears twice in a row.
MULTIPLE_DECIMALSMore than one decimal separator.
MIXED_GROUPSTwo different group separators in one number.
INVALID_GROUPINGGroup separators in the wrong place, like 1,23 in en-US.
INVALID_SIGNDuplicated or conflicting signs or parentheses.
INVALID_AFFIXText before or after the number that is not a sign, percent or currency.
UNKNOWN_CURRENCYStrict mode found a currency it cannot identify.
CURRENCY_MISMATCHThe written currency differs from the currency option.
PRECISION_LOSSConverting to minor units would need rounding (strict mode).
OUT_OF_RANGEThe value is not finite, or not a safe integer where one is required.
NumberParseError.ts
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.

LocaleCity1234567.89DecimalGroupDigits
en-USNew York1,234,567.89.,latn
en-CAToronto1,234,567.89.,latn
fr-CAMontréal1 234 567,89,no-break spacelatn
es-MXMexico City1,234,567.89.,latn
pt-BRSão Paulo1.234.567,89,.latn
es-ARBuenos Aires1.234.567,89,.latn
es-COBogotá1.234.567,89,.latn
es-CLSantiago1.234.567,89,.latn
en-GBLondon1,234,567.89.,latn
de-DEBerlin1.234.567,89,.latn
fr-FRParis1 234 567,89,narrow no-break spacelatn
es-ESMadrid1.234.567,89,.latn
it-ITRome1.234.567,89,.latn
nl-NLAmsterdam1.234.567,89,.latn
pt-PTLisbon1 234 567,89,no-break spacelatn
de-CHZürich1'234'567.89.apostrophelatn
sv-SEStockholm1 234 567,89,no-break spacelatn
pl-PLWarsaw1 234 567,89,no-break spacelatn
cs-CZPrague1 234 567,89,no-break spacelatn
uk-UAKyiv1 234 567,89,no-break spacelatn
ru-RUMoscow1 234 567,89,no-break spacelatn
tr-TRIstanbul1.234.567,89,.latn
ar-EGCairo١٬٢٣٤٬٥٦٧٫٨٩٫٬arab
ar-SARiyadh١٬٢٣٤٬٥٦٧٫٨٩٫٬arab
fa-IRTehran۱٬۲۳۴٬۵۶۷٫۸۹٫٬arabext
he-ILTel Aviv1,234,567.89.,latn
sw-KENairobi1,234,567.89.,latn
en-ZAJohannesburg1 234 567,89,no-break spacelatn
en-INMumbai12,34,567.89.,latn
hi-INDelhi12,34,567.89.,latn
bn-BDDhaka১২,৩৪,৫৬৭.৮৯.,beng
ur-PKKarachi1,234,567.89.,latn
ja-JPTokyo1,234,567.89.,latn
zh-CNShanghai1,234,567.89.,latn
ko-KRSeoul1,234,567.89.,latn
th-THBangkok1,234,567.89.,latn
vi-VNHanoi1.234.567,89,.latn
id-IDJakarta1.234.567,89,.latn
en-AUSydney1,234,567.89.,latn

Runtime support#

  • Node.js 18 and newer, Deno, Bun and all modern browsers. Requires Intl.NumberFormat with formatToParts and full ICU locale data, which Node ships by default since version 13.
  • The whole library is about 7 kB gzipped. Importing only parse costs about 3.6 kB.
  • ESM (dist/index.js), CommonJS (dist/index.cjs) and type definitions for both.

Install#

Terminal
npm install numberparrot

Guides#

No match. Try parse, currency, Arabic or pt-BR.