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);
});
http://jsfiddle.net/R8JrF/
Any help is appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…