dynamically reformat input in javascript to add commas to numbers
I have an issue with number inputting. The user usually enters a large number with many zeros, and often they are missing one or two zero as it is difficult to accurately count them.
I think javascript can work this out by showing the user the number they have inducted, for开发者_如何学运维matted with commas.
eg:
input: | 1230000000000 |
Result: 1,230,000,000,000
How could this be accomplished?
Use the following function in javascript
function addCommas(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
example
addCommas('9999999.00')
// 9,999,999.00
This is an old question but still without a correct answer so, this is my dynamic solution, it takes the same addCommas function to reformat the output but add a keyup event to clean the current value ( remove ',' ) and reformat again the new value.
$('.datainto').keyup(function () {
var value = $(this).val().replace(/,/g,'');
$(this).val(addCommas(value));
});
Check the working solution here: http://jsfiddle.net/darorck/371zrjet/
In modern browsers, you can simply achieve this with toLocaleString()
console.log((1230000000000).toLocaleString());
console.log((12300000000).toLocaleString());
console.log((1230000.152).toLocaleString());
I know I'm very late for giving the answer, But still, I post this answer because this question is coming in the search result of How to add a dynamic comma in number in javascript
, So I thought I need to add an answer which is shorter and better for upcoming developers.
精彩评论