javascriptjquerynumberscurrencyautoformat

Auto format Indian currency number


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!


Solution

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