Javascript seperate string number with dots

Javascript separate string number with dots

When working with numbers in JavaScript, it's common to come across situations where you need to format them in a specific way. One common formatting requirement is to separate the digits of a number with dots. For example, instead of displaying the number as "1000000", you may want to display it as "1.000.000".

Method 1: Using toLocaleString() method

The easiest way to achieve this is by using the built-in toLocaleString() method. This method automatically formats numbers based on the user's locale settings.


let num = 1000000;
let formattedNum = num.toLocaleString();

console.log(formattedNum); // Output: "1.000.000"

As you can see, the toLocaleString() method returns a string that separates the digits with dots. This method is widely supported by modern browsers and requires no additional libraries.

Method 2: Using a regular expression

If you need more control over the formatting of the number, you can use a regular expression to insert the dots at specific intervals.


function separateNumberWithDots(num) {
  return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ".");
}

let num = 1000000;
let formattedNum = separateNumberWithDots(num);

console.log(formattedNum); // Output: "1.000.000"

In this example, we define a function called separateNumberWithDots() that takes a number as an argument. The function converts the number to a string using the toString() method and then uses a regular expression to insert dots at every third digit.

The regular expression matches any non-word boundary (\B) that is followed by a group of three digits (\d{3}). The \B ensures that we don't insert dots at the beginning of the string or after the decimal point. The (?!\d) ensures that we don't insert dots at the end of the string if there are less than three digits remaining.

This method gives you more control over the formatting, but it requires a bit more code than using toLocaleString().

Conclusion

In conclusion, there are multiple ways to separate a string number with dots in JavaScript. You can use the built-in toLocaleString() method for a simple solution, or you can use a regular expression for more control over the formatting. Choose the method that suits your needs best!

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe