0

I am adding a comma to thousand number but those numbers have decimal value so that decimal value also added comma which I don't want

Eg: default number 2476.570550272 and I want to add comma 2,476.570550272

After using the below code I am getting comma to decimal number also like this 2,476.570,550,272.

$.fn.digits = function () {
    return this.each(function () {
        $(this).text($(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,"));
    })
}

$(".number").digits();
CBroe
  • 91,630
  • 14
  • 92
  • 150
Vishal
  • 235
  • 1
  • 15
  • 2
    You can localize numbers based on the user's language settings using the new `Intl.NumberFormat` object https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat – Derek Jul 24 '20 at 11:12
  • Does this answer your question? [How to print a number with commas as thousands separators in JavaScript](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript) – Heretic Monkey Jul 24 '20 at 11:33

3 Answers3

2

Javascript has a function for this, it's called NumberFormat:

const number = 123456.789123123123;
const yourFormat = new Intl.NumberFormat('en-EN',{ maximumFractionDigits: 5 });

console.log(yourFormat.format(number));

The function is very versatile, here you can find more options. I suggest a read for what it can do for future usage also. It has many options and is also very recommendable for currencies.

Martijn
  • 15,791
  • 4
  • 36
  • 68
1

Try with this.

function numberWithCommas(ADD-YOUR-NUM-HERE) {
    var parts = number.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}
Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
  • I think the technique of using a `parts` array and the `join` method may be cleaner than the destructuring and concatenation from my answer. – Cat Jul 26 '20 at 21:33
0

Here's a vanilla-flavored adaptation of your regex that works as you specified.

digits(document.querySelectorAll(".numInput"));

function digits(inputs){
  for(let input of inputs){
    const [int, dec] = input.value.split(".");
    input.value = int.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") + (dec ? "."+dec : "");
  }
}
<input class="numInput" value="4321.09876" />
<input class="numInput" value="987654321" />
<input class="numInput" value=".123456789" />
Cat
  • 4,141
  • 2
  • 10
  • 18