使用逗号的Javascript数字格式 [英] Javascript Number Formatting With Commas

查看:99
本文介绍了使用逗号的Javascript数字格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试格式化数字,因此每三个数字之间都有逗号。然而,它非常小故障,一旦达到8个数字就无法工作。我已将所有代码放在下面的jsfiddle中:

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/

感谢任何帮助!

推荐答案

即兴创作评论中的答案。您需要的是以下代码。检查这个以及小提琴:

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



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



它不起作用的原因是,一旦你做了更改,你需要删除所有的逗号,并再次进行格式化,这在OP的代码和其他答案代码中都没有。

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.

这篇关于使用逗号的Javascript数字格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆