How to Parse a String with Commas to a Number in JavaScript
When working with numbers formatted for human readability, you'll often encounter strings that use commas as thousands separators (e.g., "1,234,567.89"). Before you can perform any mathematical operations on this value, you must first parse it into a standard number by removing the commas.
This guide will teach you the modern and most direct way to solve this problem using the String.prototype.replaceAll() method, followed by a standard parsing function like parseFloat().
The Core Problem: Commas Make a String Non-Numeric
JavaScript's built-in parsing functions, parseInt() and parseFloat(), are designed to read a string from left to right and will stop as soon as they encounter a character they don't recognize.
Example of the problem:
// Problem: The comma causes the parsing to stop prematurely.
let numberString = '1,234,567.89';
let result = parseFloat(numberString);
console.log(result); // Output: 1 (This is not what we want!)
Here, the parseFloat() function reads "1" and then stops at the comma, returning only the number it has parsed so far. To fix this, we must first remove all the commas from the string.
The Solution: replaceAll() and parseFloat()
The most modern and readable way to remove all commas is with the String.prototype.replaceAll() method. After removing the commas, you can safely parse the resulting string.
let numberString = '1,234,567.89';
// 1. Remove all commas from the string.
let cleanString = numberString.replaceAll(',', ''); // '1234567.89'
// 2. Parse the cleaned string into a number.
let number = parseFloat(cleanString);
console.log(number); // Output: 1234567.89
This is the recommended best practice for its clarity and efficiency.
How the Solution Works
-
numberString.replaceAll(',', ''):- This method finds every occurrence of the first argument (
',') in the string and replaces it with the second argument ('', an empty string). - It returns a new string,
1234567.89, which is now a valid numeric format. - Important:
replaceAll()does not modify the original string; it returns a new one.
- This method finds every occurrence of the first argument (
-
parseFloat(cleanString):- This global function takes the "clean" string and parses it into a floating-point number.
- If you are only working with integers, you could use
parseInt(cleanString, 10)instead.
Creating a Reusable Parsing Function
If you need to perform this conversion frequently, it's a good idea to create a reusable function that encapsulates this logic and handles potential errors.
Solution:
/**
* Parses a string with thousands separators into a number.
* @param {string} str - The string to parse, e.g., "1,234.56".
* @returns {number} The parsed number, or NaN if invalid.
*/
function parseFormattedNumber(str) {
// Return 0 or NaN for empty or non-string inputs
if (!str || typeof str !== 'string') {
return NaN;
}
let cleanString = str.replaceAll(',', '');
let number = parseFloat(cleanString);
return number;
}
// Example Usage:
console.log(parseFormattedNumber('1,234,567.89')); // Output: 1234567.89
console.log(parseFormattedNumber('100')); // Output: 100
console.log(parseFormattedNumber('not a number')); // Output: NaN
An Alternative: replace() with a Regular Expression
Before replaceAll() was widely available, the standard way to replace all occurrences was to use replace() with a regular expression and the global (g) flag.
Solution:
let numberString = '1,234,567.89';
// The regex /,/g finds all comma characters globally.
let cleanString = numberString.replace(/,/g, '');
let number = parseFloat(cleanString);
console.log(number); // Output: 1234567.89
While this works perfectly, replaceAll() is now the preferred method for simple, literal replacements because it is more explicit and doesn't require knowledge of regular expressions.
Conclusion
Parsing a string with comma separators is a simple task if you follow the correct two-step process.
- The recommended best practice is to first remove all commas with
string.replaceAll(',', ''). - Then, convert the resulting clean string to a number using
parseFloat()for decimals orparseInt()for integers. - The older
string.replace(/,/g, '')method is a valid alternative butreplaceAll()is more modern and readable for this specific task.