jQuery Javascript 数字格式与逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16902924/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 18:01:07  来源:igfitidea点击:

Javascript Number Formatting With Commas

javascriptjquery

提问by MrGrinst

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:

我正在尝试格式化数字,以便每 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/

http://jsfiddle.net/R8JrF/

Any help is appreciated!

任何帮助表示赞赏!

回答by Praveen Kumar Purushothaman

I improvisedthe 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/

小提琴: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.

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

回答by optimistanoop

Use Number.prototype.toLocaleString();check here

在这里使用Number.prototype.toLocaleString();检查

var no = 3456;
no.toLocaleString(); 

Gives 3,456

给 3,456

回答by Bergi

Your problem is that when you get to the 8th digit, the intermediate result has already two commas in it. Yet,

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

val = val.replace(',', '');

does only replace the first one. You would need to provide a regular expression with the globalflag set:

只替换第一个。您需要提供带有全局标志集的正则表达式:

val = val.replace(/,/g, '');

Updated, working fiddle

更新,工作小提琴

回答by Taron Hambardzumyan

Try Intl.NumberFormatinstead

尝试Intl.NumberFormat代替

var number = 1000000;

console.log(new Intl.NumberFormat().format(number));
// 1,000,000

Solution of your issue: https://jsfiddle.net/mf2s48jo/

您的问题的解决方案:https: //jsfiddle.net/mf2s48jo/