21

我正在尝试格式化数字,以便它们每 3 个数字之间有逗号。但是,它非常有故障,一旦达到 8 个数字就不起作用。我已将所有代码放在下面的 jsfiddle 中:

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/

任何帮助表示赞赏!

4

5 回答 5

28

我在评论中即兴回答。您只需要以下代码。看看这个和小提琴:

$(document).on('keyup', '.test', function() {
    var x = $(this).val();
    $(this).val(x.toString().replace(/,/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ","));
});

小提琴:http: //jsfiddle.net/praveenscience/R8JrF/1/

它不起作用的原因是,一旦您进行了更改,您需要删除所有逗号,然后再次进行格式化,这在 OP 的代码以及其他答案代码中都没有完成。

于 2013-06-03T18:04:03.420 回答
15

Use Number.prototype.toLocaleString(); check here

var no = 3456;
no.toLocaleString(); 

Gives 3,456

于 2016-12-08T08:23:49.750 回答
5

您的问题是,当您到达第 8 位时,中间结果中已经有两个逗号。然而,

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

于 2013-06-03T18:08:38.780 回答
5

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/

于 2020-05-08T11:45:46.970 回答
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);
    }
});
于 2020-09-01T01:40:55.143 回答