numberparrot

Parse a Currency String to a Number in JavaScript (R$, €, ₹, CHF)

Prices come with symbols, codes, spaces and parentheses. Here is how to get the amount and the currency out safely.

The broken approach: strip everything that is not a digit

example.ts
const toNumber = (s) => parseFloat(s.replace(/[^0-9.-]/g, ""));

toNumber("$1,234.56");     // 1234.56   fine
toNumber("R$ 1.234,56");   // 1.23456   wrong
toNumber("1 234,56 €");    // 123456    wrong
toNumber("($1,234.56)");   // 1234.56   wrong sign

The regex cannot know whether . and , are decimal or group separators, drops the accounting parentheses, and throws away the currency.

The fix: parseCurrency

example.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");    // { amount: 1234.56, currency: "EUR", ... }
parseCurrency("₹12,34,567.89", "en-IN"); // { amount: 1234567.89, currency: "INR", ... }
parseCurrency("CHF 1'234.50", "de-CH");  // { amount: 1234.5, currency: "CHF", ... }
parseCurrency("($1,234.56)", "en-US");   // { amount: -1234.56, currency: "USD", ... }
parseCurrency("1.234,56 EUR", "de-DE");  // ISO codes work too

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. Unknown currency text gives currency: null, or an error in strict mode.

Exact cents for money

Never multiply a float by 100 to get cents: 0.29 * 100 is 28.999999999999996. Ask for minor units instead; numberparrot shifts the decimal digits as text:

example.ts
parseCurrency("0,29", "pt-BR", { toMinorUnits: true }).amount;    // 29
parseCurrency("R$ 19,99", "pt-BR", { toMinorUnits: true }).amount; // 1999
parseCurrency("¥1,235", "ja-JP", { toMinorUnits: true }).amount;   // 1235 (JPY has no minor unit)
parseCurrency("$1.005", "en-US", { toMinorUnits: true, strict: true });
// throws PRECISION_LOSS: USD has 2 decimals

Default currency

example.ts
parseCurrency("12,50", "pt-BR", { currency: "BRL" });
// { amount: 12.5, currency: "BRL", symbol: null, fractionDigits: 2 }

Install

Terminal
npm install numberparrot

Zero dependencies, ESM and CommonJS, TypeScript types included. Works in Node.js 18+, Deno, Bun and browsers. Try it in the playground.

More guides