How do I round millions and thousands in JavaScript?

denis picture denis · Oct 15, 2012 · Viewed 14.4k times · Source

I am trying to round large digits. For instance, if I have this number:

12,645,982

I want to round this number and display it as:

13 mil

Or, if I have this number:

1,345

I want to round it and display it as:

1 thousand

How do I do this in JavaScript or jQuery?

Answer

Paul Sweatte picture Paul Sweatte · Jun 6, 2013

Here is a utility function to format thousands, millions, and billions:

function MoneyFormat(labelValue) 
  {
  // Nine Zeroes for Billions
  return Math.abs(Number(labelValue)) >= 1.0e+9

       ? Math.abs(Number(labelValue)) / 1.0e+9 + "B"
       // Six Zeroes for Millions 
       : Math.abs(Number(labelValue)) >= 1.0e+6

       ? Math.abs(Number(labelValue)) / 1.0e+6 + "M"
       // Three Zeroes for Thousands
       : Math.abs(Number(labelValue)) >= 1.0e+3

       ? Math.abs(Number(labelValue)) / 1.0e+3 + "K"

       : Math.abs(Number(labelValue));

   }

Usage:

   var foo = MoneyFormat(1355);
   //Reformat result to one decimal place
   console.log(parseFloat(foo).toPrecision(2) + foo.replace(/[^B|M|K]/g,""))

References