Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I round millions and thousands in JavaScript?

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?

like image 801
denis Avatar asked Oct 15 '12 16:10

denis


People also ask

How do you round thousands in JavaScript?

How do you round to the nearest thousandth in Javascript? round(1000*X)/1000; // round X to thousandths To convert a number to a string that represents your number with exactly n decimal places, use the toFixed method.

How do you round a figure in JavaScript?

The Math. round() method rounds a number to the nearest integer. 2.49 will be rounded down (2), and 2.5 will be rounded up (3).

How do you format numbers in JavaScript?

The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in the above syntax using the '. ' operator.


2 Answers

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

  • ECMAScript-5: Annex A

  • Displaying numbers in JavaScript

like image 84
Paul Sweatte Avatar answered Sep 25 '22 17:09

Paul Sweatte


Numeral JS .. If someone checks this out please check numeral Js. you just have to include the script and then its just one lineof code

numeral(yourNumber).format('0.0a')
like image 24
Vatsal Avatar answered Sep 24 '22 17:09

Vatsal