3

I have requirement to split huge numbers in a format separated by commas but at the last 3 character i want to put comma before . for e.g 426,753,890 for such i want to put like 42,67,53,890

  function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
  }
  
  console.log(numberWithCommas(426753890));
Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
new user
  • 101
  • 1
  • 6
  • 1
    You want commas every 2 digits, except for the last 3 digits? That's a very strange format. – Barmar Jun 14 '18 at 02:19
  • 2
    @Barmar It's what is used in the [Indian system](https://en.wikipedia.org/wiki/Indian_numbering_system). Not that strange, really :-) – Vasan Jun 14 '18 at 02:20
  • Also the way you are adding comma after 3 digit is also bit lengthy. You can simply do it by `number.toLocaleString("en")`. Check this answer for more info: https://stackoverflow.com/a/50839440/631803 – Vikasdeep Singh Jun 14 '18 at 02:21

3 Answers3

2

You can do it using number.toLocaleString("en-IN") JavaScript API. number.toLocaleString() is pretty useful.

Check below examples:

let number = 426753890;

console.log(number.toLocaleString("en")); // General English format

console.log(number.toLocaleString("en-IN")); // Indian English format

Check here for reference.

Vikasdeep Singh
  • 20,983
  • 15
  • 78
  • 104
1

Correcting @VicJordan's answer, if you use en-IN locale, you should be able to get the formatted string correctly:

let number = 12345678;
console.log(number.toLocaleString("en-IN"));
31piy
  • 23,323
  • 6
  • 47
  • 67
1

Here is a tricky example to do so...

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].substring(0, parts[0].length-1).replace(/\B(?=(\d{2})+(?!\d))/g, ",") + parts[0].substring(parts[0].length-1);
    return parts.join(".");
  }
  
  console.log(numberWithCommas(426753890));
Terry Wei
  • 1,521
  • 8
  • 16