Skip to content

toNumber

Extracts a numeric value from a string by stripping non-digit characters, respecting the locale’s decimal and group separators. Uses Intl.NumberFormat to determine the separators for the given locale.

import { toNumber } from "1o1-utils";
import { toNumber } from "1o1-utils/to-number";
function toNumber(params: { value: string; locale?: string }): number
NameTypeRequiredDescription
valuestringYesThe string to parse
localestringNoBCP 47 locale tag controlling decimal/group separators. Defaults en-US

number — The numeric value parsed from value.

toNumber({ value: "R$ 1.500,00", locale: "pt-BR" }); // 1500
toNumber({ value: "12,5", locale: "pt-BR" }); // 12.5
toNumber({ value: "12.5" }); // 12.5
toNumber({ value: "123abc456" }); // 123456
// Negative values via leading "-" or Unicode "−"
toNumber({ value: "-1,234.56" }); // -1234.56
toNumber({ value: "−42" }); // -42
// Thousands separators are stripped per locale
toNumber({ value: "1,234,567.89", locale: "en-US" }); // 1234567.89
toNumber({ value: "1.234.567,89", locale: "pt-BR" }); // 1234567.89
  • Throws TypeError if value is not a string.
  • Throws if value contains no digits (empty string, "abc", "R$ ,").
  • Throws if the cleaned value cannot be parsed (e.g. multiple decimal separators like "1.2.3" in en-US).
  • A - appearing after the first digit is treated as a separator, not a sign ("12-34"1234).
  • Locales with non-breaking space group separators (e.g. fr-FR) work as expected — any unrecognized character is simply stripped.
  • ASCII digits only. Non-ASCII digit scripts (Arabic-Indic ١٢٣, Devanagari १२३, etc.) are stripped along with other non-digit characters, even when the locale would format with them. Convert to ASCII digits before calling toNumber if needed.
  • No scientific notation. Inputs like "1e5" produce 15 (the e is stripped as a non-digit), not 100000. Parse scientific notation with Number() or parseFloat directly.
  • The internal separator cache is bounded to the 32 most-recently-seen locales (FIFO) to keep memory predictable when many locales are queried.

parseNumber, numeric extract, strip non-digits, currency parse, locale-aware number parse

I'm using 1o1-utils (npm: https://www.npmjs.com/package/1o1-utils, GitHub: https://github.com/pedrotroccoli/1o1-utils, LLM context: https://pedrotroccoli.github.io/1o1-utils/llms.txt). Show me how to use toNumber to parse a Brazilian currency string like "R$ 1.500,00" into a number.