Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add commas for a number in input field while typing

Tags:

jquery

This does it incorrectly: Can jQuery add commas while user typing numbers?

  $('input.number').keypress(function(event){
      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var $this = $(this);
      var num = $this.val().replace(/,/g, '');
      $this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,"));
  });

I need "1000000" to be "1,000,000" or better with spaces "1 000 000".

Please help. Thanks.

like image 974
Alex G Avatar asked Feb 06 '12 06:02

Alex G


People also ask

How do you add commas to numbers?

First comma is placed three digits from the right of the number to form thousands, second comma is placed next two digits from the right of the number, to mark lakhs and third comma is placed after another next two digits from the right to mark crore, in Indian system of numeration.

How do you convert a number to a comma separated string?

Using toLocaleString() method The JavaScript toLocaleString() method is used to convert the elements of the given array into a string, and these Strings are separated by a comma ",".

How do you add commas in numbers in Java?

You can use java. util. text. NumberFormat class and its method setGroupingUsed(true) and setGroupingSize(3) to group numbers and add a comma between them.

How do you add a comma in a price in react JS?

To format a number with commas in React, we can use the number's toLocaleString method. We call toLocaleString on 1234.56789 with { maximumFractionDigits: 2 } to return a number string that has the comma digit separators and the rounded to 2 decimal places.


2 Answers

if you wanted to have something like "1 000 000", you can change the code to something like this.

  var num = $this.val().replace(/(\s)/g, '');
  $this.val(num.replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1 "));

Hope this helps

like image 108
XepterX Avatar answered Oct 25 '22 09:10

XepterX


$(document).ready(function(){


    $('input.number').keyup(function(event){
      // skip for arrow keys
      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var $this = $(this);
      var num = $this.val().replace(/,/gi, "").split("").reverse().join("");

      var num2 = RemoveRougeChar(num.replace(/(.{3})/g,"$1,").split("").reverse().join(""));

      // the following line has been simplified. Revision history contains original.
      $this.val(num2);});});

    function RemoveRougeChar(convertString){


    if(convertString.substring(0,1) == ","){

        return convertString.substring(1, convertString.length)            

    }
    return convertString;

}

Edit as you see fit - also in jsfiddle - jsFiddle

like image 20
CR41G14 Avatar answered Oct 25 '22 10:10

CR41G14