Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
4
rated 0 times [  8] [ 4]  / answers: 1 / hits: 47213  / 11 Years ago, mon, june 3, 2013, 12:00:00

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!


More From » jquery

 Answers
4

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, ,));
});


Fiddle: http://jsfiddle.net/praveenscience/R8JrF/1/



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.


[#77844] Sunday, June 2, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
santiago

Total Points: 375
Total Questions: 106
Total Answers: 97

Location: Argentina
Member since Thu, Mar 18, 2021
3 Years ago
;