Skip to content

How to change commas into dots with JavaScript

New Course Coming Soon:

Get Really Good at Git

I had a problem: 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.

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.

This is not something that applies to our use case, and I think we need to do more validation to check the integrity of our input here, but it’s a start.

In my case, after doing this substitution I called parseFloat(value) to get the float from the string, and then I limited the decimals number to 2 using toFixed(2):

value = parseFloat(value).toFixed(2)
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: