Auto format Indian currency number

95 Views Asked by At

I am using following code to display currency in Indian numbering system:

<script type="text/javascript">
   function format(obj) {
      var formatted = obj.value.replace(/\D/g, '');
      obj.value = formatted.replace(/(\d+)(\d{2})/g,'$1.$2');
   }
</script>

<input type="number" onkeyup="format(this)">

Output I'm getting: 123456.78

Output I want is: 1,23,45,678.00

Please help!

2

There are 2 best solutions below

0
On BEST ANSWER

You can use Intl.NumberFormat

const number = 12345678;
console.log(new Intl.NumberFormat('en-IN').format(number));

If that should be a currency, you can pass that as a second argument

const number = 12345678;
console.log(new Intl.NumberFormat('en-IN', {style: 'currency', currency: 'INR'}).format(number));

Or to force the two decimals:

const number = 12345678;
console.log(new Intl.NumberFormat('en-IN', {minimumFractionDigits: 2}).format(number));

0
On

Number.prototype.toLocaleString() will be of great help here.

function convertToIndianCurrency(x){
  return x.toLocaleString('en-IN');
}

console.log(convertToIndianCurrency(123456.789));