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.
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.
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 ",".
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.
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.
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
$(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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With