17

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)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
  }) 
}

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

Jeff
  • 1,152
  • 5
  • 14
  • 27

2 Answers2

57

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

Rion Williams
  • 74,820
  • 37
  • 200
  • 327
  • 1
    dang that's a nice regex. Last time I solved this I ended up splitting the string _again_ to reverse it, insert commas into the array, and join again. – Evan Davis Dec 28 '12 at 20:10
  • If using this with currency - which doesn't always have the decimals - adding yourNumber=yourNumber.toFixed(2) to the beginning sets it to always show the decimals even if they are 0 – DB---- Apr 03 '14 at 13:32
  • this didn't work for me "as the user types" unless i added yourNumber = yourNumber.replace(/,/g, ""); first – Taylor Brown May 14 '14 at 22:03
  • best one for a number with decimal – Arzon Barua Aug 08 '17 at 11:27
  • still nice and simple. and you can easily switch the commas and dots depending on what you need – FilT Jan 16 '21 at 20:29
2

I use accounting.js lib:

accounting.format(1136.6696, 4) // 1,136.6696
Artem P
  • 5,198
  • 5
  • 40
  • 44