0

How to convert a number in Indian currency to show in html?

   var formatter = new Intl.NumberFormat('en-IN', {
      style: 'currency',
      currency: 'INR',
      minimumFractionDigits: 2,
      });

    $( document ).ready(function() {
        var sum = 0;
        $(".number").each(function(){
            sum += +$(this).val();
        });
         $(".total").val(formatter.format(sum));
    });
James Z
  • 12,209
  • 10
  • 24
  • 44

1 Answers1

0

Your code seems to format the number correctly.

If you problem is how to keep calculating the sum when the user changes the values in the .number fields, then you need to add an event handler for the input event and do the calculation again.

var formatter = new Intl.NumberFormat('en-IN', {
  style: 'currency',
  currency: 'INR',
  minimumFractionDigits: 2,
});

function calculateSum() {
  var sum = 0;
  $(".number").each(function() {
    sum += +$(this).val();
  });
  $(".total").val(formatter.format(sum));
}

$(document).ready(function() {
  $('.number').on('input', calculateSum);
  
  calculateSum();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<input class="number" value=""><br/>
<input class="number" value=""><br/>
<input class="number" value=""><br/>
<input class="number" value=""><br/>

<input class="total">
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Thanks for your valuable help. Actually, I am fetching data into a table from the database. the numbers are showing correctly, only the thing is am not getting it converted into the currency. (No User input is required). getting an error at console - jquery.min.js:4 The specified value "\u20B97,52,272.00" cannot be parsed, or is out of range. – Prasad Todkari Feb 27 '21 at 10:36
  • @PrasadTodkari you might want to look at https://stackoverflow.com/questions/29255843/is-there-a-way-to-reverse-the-formatting-by-intl-numberformat-in-javascript for the reverse process (*extracting a number from a formatted string*) – Gabriele Petrioli Mar 03 '21 at 15:41