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.
Try it
Section titled “Try it”Import
Section titled “Import”import { toNumber } from "1o1-utils";import { toNumber } from "1o1-utils/to-number";Signature
Section titled “Signature”function toNumber(params: { value: string; locale?: string }): numberParameters
Section titled “Parameters”| Name | Type | Required | Description |
|---|---|---|---|
| value | string | Yes | The string to parse |
| locale | string | No | BCP 47 locale tag controlling decimal/group separators. Defaults en-US |
Returns
Section titled “Returns”number — The numeric value parsed from value.
Examples
Section titled “Examples”toNumber({ value: "R$ 1.500,00", locale: "pt-BR" }); // 1500toNumber({ value: "12,5", locale: "pt-BR" }); // 12.5toNumber({ value: "12.5" }); // 12.5toNumber({ value: "123abc456" }); // 123456// Negative values via leading "-" or Unicode "−"toNumber({ value: "-1,234.56" }); // -1234.56toNumber({ value: "−42" }); // -42// Thousands separators are stripped per localetoNumber({ value: "1,234,567.89", locale: "en-US" }); // 1234567.89toNumber({ value: "1.234.567,89", locale: "pt-BR" }); // 1234567.89Edge Cases
Section titled “Edge Cases”- Throws
TypeErrorifvalueis not a string. - Throws if
valuecontains no digits (empty string,"abc","R$ ,"). - Throws if the cleaned value cannot be parsed (e.g. multiple decimal separators like
"1.2.3"inen-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 callingtoNumberif needed. - No scientific notation. Inputs like
"1e5"produce15(theeis stripped as a non-digit), not100000. Parse scientific notation withNumber()orparseFloatdirectly. - The internal separator cache is bounded to the 32 most-recently-seen locales (FIFO) to keep memory predictable when many locales are queried.
Also known as
Section titled “Also known as”parseNumber, numeric extract, strip non-digits, currency parse, locale-aware number parse
Prompt suggestion
Section titled “Prompt suggestion”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.