How to convert a currency string to a double with Javascript?
We'll use parseFloat
partnered with a regex to strip unwanted characters:
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.
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:
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:
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:
Handling unique currency formats
Here's how to ensure your regex handles both leading/trailing currency symbols and negative values:
This regex accepts parentheses for negative amounts and strips symbols commonly used in accounting.
Was this article helpful?