Skip to content

Locale string to number JavaScript | Example code

  • by

Use JavaScript toLocaleString method to convert the Locale string into a number.

An easy way to convert a string that might contain commas to a number is to find any non-digits within the string and remove it, thus, remaining with only digits.

var num = number.toLocaleString().replace(/\D/g,''); //1000000

Locale string to number JavaScript

Simple example code.

 <!DOCTYPE html>
 <html>
 <body>

  <script>
    var number = 1000000;
    console.log('numeric number', number); 

    var str = number.toLocaleString();  
    console.log('with commas', str);  

    var num = str.replace(/\D/g,'');
    console.log('string without commas', num);  

    var num2 = parseInt(num);
    console.log('numeric', num2);  
  </script>

</body>
</html> 

Output:

Locale string to number JavaScript

Source: stackoverflow.com

How to convert String to Number according to locale JavaScript?

Answer: The following function will first construct a NumberFormat based on the given locale. Then it will try to find the decimal separator for that language.

Finally, it will replace all but the decimal separator in the given string, then replace the locale-dependant separator with the default dot and convert it into a number.

<script>
    function convertNumber(num, locale) {
      const { format } = new Intl.NumberFormat(locale);
      const [, decimalSign] = /^0(.)1$/.exec(format(0.1));
      return +num
      .replace(new RegExp(`[^${decimalSign}\\d]`, 'g'), '')
      .replace(decimalSign, '.');
    };

    console.log(convertNumber('100,45', 'de-DE'))
</script>

Output: 100.45

Do comment if you have any doubts or suggestions on this JS local string topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading