Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - jQuery function to to format number with commas and decimal

I'm using the following function to format numbers as the user types. It will insert a comma every 3 numbers. Ex: 45696.36 becomes 45,696.36.

However, I've run into a problem with it. If the numbers after the decimal are longer than 3 digits, it starts adding commas to them. Ex: 1136.6696 becomes 1,136.6,696.

This is my function:

$.fn.digits = function(){
  return this.each(function() {
    $(this).val( $(this).val().replace(/[^0-9.-]/g, '') );
    $(this).val( $(this).val().replace(/(d)(?=(ddd)+(?!d))/g, "$1,") ); 
  }) 
}

How can I fix this so it stops placing commas after the decimal? I'm using jQuery 1.8. Thanks!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

You could accomplish this by splitting your string at the '.' character and then performing your comma-conversion on the first section only, as such:

function ReplaceNumberWithCommas(yourNumber) {
    //Seperates the components of the number
    var n= yourNumber.toString().split(".");
    //Comma-fies the first part
    n[0] = n[0].replace(/B(?=(d{3})+(?!d))/g, ",");
    //Combines the two sections
    return n.join(".");
}

ReplaceNumberWithCommas(1136.6696); //yields 1,136.6696

Example


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...