Skip to content

HTML input format number thousands separator | Example code

  • by

To get HTML format number thousands separator in the input field you have to use JavaScript code. Where replace method and regular expression is required.

HTML format number thousands separator example

Simple example code entering 12000 and it looks like 12,000 in the textbox.

<!doctype html>

    // insert commas as thousands separators 
    function addCommas(n){
      var rx=  /(\d+)(\d{3})/;
      return String(n).replace(/^\d+/, function(w){
          w= w.replace(rx, '$1,$2');
        return w;

    // return integers and decimal numbers from input
    // optionally truncates decimals- does not 'round' input

    function validDigits(n, dec){
      n= n.replace(/[^\d\.]+/g, '');
      var ax1= n.indexOf('.'), ax2= -1;
      if(ax1!= -1){
        ax2= n.indexOf('.', ax1);
        if(ax2> ax1) n= n.substring(0, ax2);
        if(typeof dec=== 'number') n= n.substring(0, ax1+dec);
      return n;
    window.onload= function(){
      var n1= document.getElementById('number1'),
      n2= document.getElementById('number2');

      n1.onkeyup= n1.onchange=n2.onkeyup=n2.onchange= function(e){
        e=e|| window.event; 
        var || e.srcElement,temp;
        if('number2')  temp= validDigits(who.value,2); 
        else temp= validDigits(who.value);
        who.value= addCommas(temp);
      n1.onblur= n2.onblur= function(){
        var temp=parseFloat(validDigits(n1.value)),
  <h1>Input Thousands Commas</h1>
      <label> Any number <input id="number1" value=""></label>
      <label>2 decimal places <input id="number2" value=""></label>


HTML format number thousands separator input

Another way is to use Intl.NumberFormat() method.


      givenNumber = 123456789;

      nfObject = new Intl.NumberFormat('en-US');
      output = nfObject.format(givenNumber);



Output: 123,456,789

Do comment if you have any doubts or suggestions on this HTML code.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *