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));

3
  • 1
    You want commas every 2 digits, except for the last 3 digits? That's a very strange format. Commented Jun 14, 2018 at 2:19
  • 2
    @Barmar It's what is used in the Indian system. Not that strange, really :-) Commented Jun 14, 2018 at 2: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: stackoverflow.com/a/50839440/631803 Commented Jun 14, 2018 at 2:21

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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"));

Comments

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));

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.