Reputation: 1000
I'm trying to format numbers so they have commas between every 3 numbers. It is very glitchy however and doesn't work once it gets to 8 numbers. I've put all the code in a jsfiddle below:
function commaSeparateNumber(val){
val = val.replace(',', '');
var array = val.split('');
var index = -3;
while (array.length + index > 0) {
array.splice(index, 0, ',');
// Decrement by 4 since we just added another unit to the array.
index -= 4;
}
return array.join('');
};
$(document).on('keyup', '.test', function() {
var value = $(this).val();
value = commaSeparateNumber(value);
$(this).val(value);
});
Any help is appreciated!
Upvotes: 22
Views: 49095
Reputation: 3805
I know, this is an old question. However, I wanted to keep my cursor at the same position within the number even while the text was getting longer or shorter depending on the number of commas being added or removed. In the end this is what I used. Now, if I put my cursor anywhere within my input field and change it, it will not move my cursor to the end of the number or jump around within the number.
jQuery(document).on('keyup', '.number-format', function(_e) {
var _x = jQuery(this).val();
var _cursor = _e.target.selectionStart;
var _length = _x.toString().replace(/,/g, "").length;
var _commas = _x.length - _length;
jQuery(this).val(_x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
var _newLength = _x.toString().replace(/,/g, "").length;
var _newCommas = jQuery(this).val().length - _newLength - _commas;
if (_newLength == _length && _newCommas == 0) {
_e.target.setSelectionRange(_cursor, _cursor);
}else{
_e.target.setSelectionRange(_cursor - (_newLength - _length) + _newCommas, _cursor - (_newLength - _length) + _newCommas);
}
});
Upvotes: 0
Reputation: 151
Try Intl.NumberFormat instead
var number = 1000000;
console.log(new Intl.NumberFormat().format(number));
// 1,000,000
Solution of your issue: https://jsfiddle.net/mf2s48jo/
Upvotes: 7
Reputation: 952
Use Number.prototype.toLocaleString();
check here
var no = 3456;
no.toLocaleString();
Gives 3,456
Upvotes: 16
Reputation: 664538
Your problem is that when you get to the 8th digit, the intermediate result has already two commas in it. Yet,
val = val.replace(',', '');
does only replace the first one. You would need to provide a regular expression with the global flag set:
val = val.replace(/,/g, '');
Upvotes: 5
Reputation: 167182
I improvised the answer in the comment. What you would need is the below code only. Check this out and also the fiddle:
$(document).on('keyup', '.test', function() {
var x = $(this).val();
$(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
});
The reason why it didn't work was, once you make changes, you need to remove all the commas, and do the formatting again, which was not done in the OP's code as well as the other answer code.
Upvotes: 28