Kodeclik Blog


How to add commas to a Javascript number

To add commas to a JavaScript number, we can use two possible methods. We can employ the toLocaleString() method, or use regular expressions.

Method 1: Use the toLocaleString() method

Here is some possible code and a form to test this idea:
This code creates a form with an input field and a button. When the button is clicked, it calls the addCommas() function. This function gets the value of the input field and converts it to a number using the Number() constructor. If the input is not a number, it displays a message saying so. If it is a number, it uses the toLocaleString() method to add commas to the number. The message is displayed in a paragraph element with the id "result".
Here is an example of this approach in action:

Method 2: Use regular expressions

Here is a second approach using regular expressions:
In this approach, again we create a form with an input field and a button. When the button is clicked, it calls the addCommas() function. (Thus far the code is the same). The function as usual gets the value of the input field and converts it to a number using the Number() constructor. If the input is not a number, it displays a message saying so. If it is a number, it uses a regular expression to add commas to the number. The regular expression /\B(?=(\d3)+(?!\d))/g matches any non-word boundary (\B) that is followed by a group of three digits ((\d3)) that is not followed by another digit ((?!\d)). The replace() method replaces all matches with a comma. Finally as before, the message is displayed in a paragraph element with the id "result".
Here is an example of this program (try it out yourself):
If you liked this blogpost, checkout our post on how to test if a Javascript string is a number.
Want to learn Javascript with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.
  • ABOUT

Copyright @ Kodeclik 2024. All rights reserved.