Skip to content

How to change commas into dots with JavaScript

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)

→ Get my JavaScript Beginner's Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about js: