adding zero decimal with java script

I have a code like this in my view:

<div id="price"> 2000000 </div>

I want a Javascript code that add "," for each three digits from right and in my code it's should be: 2,000,000

I'm beginner in javascript and i seen a few topics about this code and none of them was complete (with html codes) , please explain how i use this javascript code in my html code How can I do this?

Upvotes: 0

Views: 38

Answers (2)

BlackPearl
BlackPearl

Reputation: 1662

You can use toLocaleString() method on a number in javascript, to get your required result.

var priceDiv = document.getElementById("price")
var price = +priceDiv.innerHTML;
priceDiv.innerHTML = price.toLocaleString()
<div id="price"> 2000000 </div>

More on toLocaleString : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

Upvotes: 0

Abhijit Sil
Abhijit Sil

Reputation: 191

use n.toLocaleString(). it will convert number to comma separated number.

Upvotes: 1

Related Questions