Explain Codes LogoExplain Codes Logo

How to convert a currency string to a double with Javascript?

javascript
prompt-engineering
functions
regex
Alex KataevbyAlex Kataev·Dec 17, 2024
TLDR

We'll use parseFloat partnered with a regex to strip unwanted characters:

let number = parseFloat("$1,234.56".replace(/[^\d.-]/g, '')); console.log(number); // it's 1234.56, not rocket science

Here, .replace(/[^\d.-]/g, '') is doing a clean-up, removing anything that's not a digit or decimal. Then parseFloat steps in, doing the heavy lifting.

Handling various currency symbols

Now, if you're dealing with euros, pounds or anything that's not a dollar, we have to tweak our regex to account for different symbols and separators.

let number = parseFloat("€1.234,56".replace(/[^\d,.-]/g, '').replace(',', '.')); console.log(number); // 1234.56, because we're not currency biased

Here, we've recognized the comma as a decimal point, which is typical in several countries. Always keep in mind: not everyone uses the same format as you do!

Using Libraries for Localization

Enter jQuery Globalize when we're dealing with multiple locales:

Globalize.culture('fr-FR'); // French, because why not? let number = Globalize.parseFloat("1 234,56 €"); console.log(number); // 1234.56, Oui, c'est vrai!

With Globalize, we can handle locale-specific parsing without breaking a sweat.

Dealing with floating-point precision

Working with currency requires accuracy. But remember: JavaScript has a mind of its own when it comes to precision:

let number = parseFloat("1000000000000000000.99".replace(/[^\d.-]/g, '')); console.log(number); // 1000000000000000000, NOT 1000000000000000000.99 - JavaScript, why?

Here, consider using libraries such as Big.js or Decimal.js for precise operations.

Advanced parsing with libraries

If your case involves various currency formats, consider using accounting.js. It offers accurate parsing beyond common formats:

let number = accounting.unformat("$1,234,567.89"); console.log(number); // 1234567.89 because we mean business!

Handling unique currency formats

Here's how to ensure your regex handles both leading/trailing currency symbols and negative values:

let euNumber = parseFloat("-€123.456,78".replace(/[^\d,.-]/g, '').replace(',', '.')); let usNumber = parseFloat("($123,456.78)".replace(/[^\d.-]/g, '')); console.log(euNumber); // -123456.78, because even money can have a rough day console.log(usNumber); // -123456.78, yes, it was a big party

This regex accepts parentheses for negative amounts and strips symbols commonly used in accounting.