21

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!

MrGrinst
  • 970
  • 3
  • 9
  • 20

5 Answers5

28

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.

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • Erk! Now I can't use my arrow keys to move the cursor to the left! – Gareth Jun 03 '13 at 18:06
  • 1
    What? Wait. Lemme check and return a better one. :P – Praveen Kumar Purushothaman Jun 03 '13 at 18:07
  • 1
    @Gareth Check the original code. It is way worse. It keeps on adding commas. :) Mine's better. Will try to fix. :) – Praveen Kumar Purushothaman Jun 03 '13 at 18:08
  • Oh your first attempt performs better than the original, but I would agree with @Bergi that this kind of formatting is not useful inside the input. You won't find a keyup solution that lets me change or add a digit in the middle of the string (and still keeps my cursor in the same place) without a lot of additional Javascript, or as I would call it "overkill" – Gareth Jun 03 '13 at 18:11
  • @Gareth Lemme say you a simple one. This issue can be tackled using `onBlur()` so that, this changing gets triggered only when the field loses focus. Does it solve? – Praveen Kumar Purushothaman Jun 03 '13 at 18:12
  • Yes, if you're happy that editing that "onblur" field can leave it temporarily looking like `1,234,55567,890`. I don't know the reason for the OP wanting commas in his input but personally I can't see the benefits, which makes it hard to know how much effort is "too much" to get it working – Gareth Jun 03 '13 at 18:16
  • Yes. I understand. But when will `1,234,55567,890` - THIS come? 55567??? Say it is a typo! – Praveen Kumar Purushothaman Jun 03 '13 at 18:17
  • 1
    let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/31141/discussion-between-gareth-and-praveen-kumar) – Gareth Jun 03 '13 at 18:17
  • when ading point for floating eg: 1,000,000.00 after this number if you add more digits the poing will replace the comma and the number will be 1,000,000.000.000 – danielpopa Oct 25 '13 at 09:29
15

Use Number.prototype.toLocaleString(); check here

var no = 3456;
no.toLocaleString(); 

Gives 3,456

optimistanoop
  • 912
  • 1
  • 11
  • 14
7

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/

5

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

Updated, working fiddle

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

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);
    }
});
James
  • 3,765
  • 4
  • 48
  • 79