Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

jquery - Javascript Number Formatting With Commas

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...