-1

I'm trying to make a calculator in JavaScript. I'd like to add a comma separator to the whole number when it displayed to input. I want to do it by using toLocaleString method but it doesn't work.

function addComma() {
  const display = document.querySelector('.display');
  let disVal = display.value;
  if (disVal !== '') {
    return display.value = Number(disVal).toLocaleString();
  }
}


Min
  • 23
  • 1
  • 4

1 Answers1

1

You have to specify the locale as in the below snippet -

function addUSComma(n) {
  const display = n;
  return display.toLocaleString('en-US');
}

function addINComma(n) {
  const display = n;
  return display.toLocaleString('en-IN');
}

console.log(addUSComma(123456789));
console.log(addINComma(123456789));

You can read more about setting locales here

Praneet Dixit
  • 1,393
  • 9
  • 25