1

I have a price div in my website like this:

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

Now I'm looking for a JavaScript method to add commas every three digits in all of my price "div"s.

Unmitigated
  • 76,500
  • 11
  • 62
  • 80
  • 1
    Does this answer your question? [How to format numbers?](https://stackoverflow.com/questions/5731193/how-to-format-numbers) – Liftoff Dec 29 '20 at 20:37
  • @David Unfortunately this in this topic they give number inline of js code, but i want add digits to my html div prices and i'm newbie in js and can't change that topic code – Seyyed Mohammad Hosseini Dec 29 '20 at 20:39
  • `parseInt(document.getElementById("price").innerHTML)` will give you the content of your div as a number. – Liftoff Dec 29 '20 at 20:40

1 Answers1

4

You can use toLocaleString.

const priceDiv = document.querySelector('#price');
priceDiv.textContent = (+priceDiv.textContent).toLocaleString('en-US');
<div id="price">20000</div>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80