If you are working with a simple website or a react application, There are 3 common situations where you have to add a comma as a thousand separators.
- Add a comma to the input field while the user is typing.
- Add a comma to static data like price in react or HTML.
Adding Comma to Input Field While the User is Typing
This is a very common use case where you want to add a comma to an input field while the user is typing. For this, you need to use the regular expression to replace the input value when the user is typing. The following example adds a comma while the user is typing.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
// HTML input <input id="number_element" type="text"> <span>.00</span> // javascript code to add comma while typing let inputElement = document.querySelector("#number_element"); inputElement.addEventListener("keyup",(event)=>{ var tempNumber = inputElement.value.replace(/,/gi, ""); var commaSeparatedNumber = tempNumber.split(/(?=(?:\d{3})+$)/).join(","); inputElement.value = commaSeparatedNumber; }) |
Please note that you can’t have a comma to a number type input because a comma is actually a string.
Using toLocalString
Javascript method to Add a comma
You can use the built-in javascript function toLocalString
to add a thousand separator commas if you are displaying information on a web page. This is very useful when you are working with a framework like React or Vue. Here is an example of the first situation.
1 2 3 4 5 6 7 8 9 10 11 12 |
// html code <span id="productPrice"></span> // javascript code const productPrice = 46753; document.querySelector("#productPrice").innerText = productPrice.toLocaleString(); console.log(productPrice.toLocalString()); // output : 46,753 |
If you are using react you can simply write the following code to make it work. You can read more about toLocaleString
javascript method at https://developer.mozilla.org.
1 2 3 4 5 6 7 8 9 |
// JSX const productPricec= = 42456; <span> {productPrice.toLocaleString()} </span> |
Conclusion
There are 2 use cases where you need to add a comma in number values. The first is when the user is typing in a form input and the second is when displaying static data like price. You can use a regular expression to add commas in the HTML input field when the user is typing. There is a build-in function toLocaleString
which is helpful when you are displaying a number value on a web page.