How to change commas into dots with JavaScript
By Flavio Copes
Learn how to change commas into dots in a JavaScript number string with a regex and replace(), then use parseFloat() and toFixed(2) to clean up the decimals.
To change commas into dots in a string, call replace() with a regular expression. Let me show you the exact problem I had, and the full solution.
I had a string that contained a decimal number, but the user could write it in two ways, using a dot, or a comma:
0,32
0.32
Different countries use different ways to separate the integral part from the decimal part of a number. Italy, for example, uses the comma. And that’s a problem: pass '0,32' to parseFloat() and you get 0, because parsing stops at the comma.
So I decided to convert the string to using a dot whenever I found a comma.
I used a simple regular expression to do that:
let value = '0,32'
value = value.replace(/,/g, '.')
//value is now '0.32'
You can do the opposite using replace(/\./g, ',') (note the \ before the . to escape it, since it’s a special character in regular expressions).
The g flag in the regex makes sure that if there are multiple instances of a comma (or dot, in the second example) they are all converted.
Modern JavaScript also gives us replaceAll(), which does the same job without a regex:
value = value.replaceAll(',', '.')
From string to number
After doing this substitution I called parseFloat(value) to get the float from the string, and then I limited the decimals to 2 using toFixed(2):
value = parseFloat(value).toFixed(2)
Be careful here: toFixed() returns a string, not a number. (0.32).toFixed(2) gives you '0.32' with quotes around it. If you need a number to do math with, parse it again:
const amount = parseFloat(parseFloat(value).toFixed(2))
Watch out for thousands separators
This naive replacement breaks if the input contains thousands separators.
In Italian formatting, 1.234,56 means one thousand two hundred thirty four, and 56 cents. Replace the comma and you get 1.234.56, which parseFloat() reads as 1.234. Wrong result, no error thrown.
The fix is to strip the dots first, then convert the comma:
let value = '1.234,56'
value = value.replace(/\./g, '').replace(/,/g, '.')
//value is now '1234.56'
This works when you know the input uses comma-decimal formatting. If users can type either format freely, you need more validation to figure out which separator is the decimal one before converting. My case was a small internal form, so the two replacements were enough.
Related posts about js: