Search code examples
javascriptformatlocale

How to format a number string to an appropriately localized display format?


I have this code that calls an API:

<script>
  setInterval(function(){ getPrintCount(); }, 1500);

  function getPrintCount(){
      $.ajax({
          url: 'https://data.memopresso.com/api/data/count',
          dataType: 'json',
          type: 'get',
          cache: false,
          success: function(data){
              document.getElementById("printCount").innerHTML = data.count;
          },
          error: function(data){
              document.getElementById("printCount").innerHTML = '0';
          }
      });
  }

I'd like to make it output numbers formatted like 9,55,100 (Indian format).

I've managed to find that

.toLocaleString('en-IN')

should solve my issue.

I try to put this into my code like this

document.getElementById("printCount").innerHTML = data.count.toLocaleString('en-IN');

but I can't make it work, the numbers still display as a plain text😢


Solution

  • It seems like in order to display the number using toLocaleString, the number must be a Number, not a String. It seems like your data.count is treated as a String. Try the following:

    document.getElementById("printCount").innerHTML = parseInt(data.count).toLocaleString('en-IN');
    

    Alternatively, if your number is a floating point number:

    document.getElementById("printCount").innerHTML = parseFloat(data.count).toLocaleString('en-IN');