We can add commas to a number in JavaScript by using the JavaScript toLocaleString() method.
var num = 1234;
var commaNum = num.toLocaleString();
When working with numbers in JavaScript, many times you need to format those numbers a certain way. One such situation is if you want to add commas to numbers in your program or application.
In JavaScript, we can easily add commas to a number by using the toLocaleString() method.
Here is our code again with some examples.
var num1 = 1234;
var num2 = 2434532.106;
var num3 = -238445;
var num4 = 203200932020;
var commaNum1 = num1.toLocaleString();
var commaNum2 = num2.toLocaleString();
var commaNum3 = num3.toLocaleString();
var commaNum4 = num4.toLocaleString();
console.log(commaNum1);
console.log(commaNum2);
console.log(commaNum3);
console.log(commaNum4);
#Output
1,234
2,434,532.106
-238,445
203,200,932,020
Add Commas to Number in JavaScript with a Click
In this simple example, we will let the user input a number, and we will add commas to it, if necessary.
Here is the HTML setup:
<div id="div1">
<label for="num1">Enter a Number:</label>
<input type="text" id="num1" name="num1">
<div id="click-me" onclick="addCommas()">Add Commas to Number</div>
<div id="results"></div>
</div>
We will add an onclick event to our #click-me div that will run a function we will create. Our function will first use the value property along with the getElementById method to get the number the user has entered.
We will then add commas to the number using the JavaScript toLocaleString() method.
We will finally post the results using the textContent property.
function addCommas(){
//Get the user number
var userNum = Number(document.getElementById("num1").value);
//Add commas to number
var commaNumber = userNum.toLocaleString();
//Display the results
document.getElementById("results").textContent = commaNumber;
}
The final code and output for adding commas to a number in JavaScript is below.
Code Output:
Full Code:
<div id="div1">
<label for="num1">Enter a Number:</label>
<input type="text" id="num1" name="num1">
<div id="click-me" onclick="addCommas()">Add Commas to Number</div>
<div id="results"></div>
</div>
<script>
function addCommas(){
var userNum = Number(document.getElementById("num1").value);
var commaNumber = userNum.toLocaleString();
document.getElementById("results").textContent = commaNumber;
};
</script>
Hopefully this article has been useful for you to learn how to add commas to a number in JavaScript.
Leave a Reply