0

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?

  • 2
    Does this answer your question? [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Matt Grande Jan 10 '20 at 19:55
  • @MattGrande I'm beginner in java script i'm not sure to how use these javascripts code in my div id – Seyyed Mohammad Hosseini Jan 10 '20 at 20:00

2 Answers2

1

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

Abhijit Sil
  • 191
  • 4
0

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

BlackPearl
  • 1,662
  • 1
  • 8
  • 16