How do I round millions and thousands in JavaScript?
Asked Answered
S

10

9

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?

Surat answered 15/10, 2012 at 16:53 Comment(1)
Yeah, I had a pretty cool answer for this but it will have to wait until next timeSchlenger
T
22

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

Trixie answered 5/6, 2013 at 22:1 Comment(3)
This works pretty well. I used it as an AngularJS filter: // adds M, B and rounds big numbers. e.g. 5.3B, 6M, mm2.filter('bigNumRound', function() { return function (val) { // Nine Zeroes for Billions return Math.abs(Number(val)) >= 1.0e+9 ? Math.abs(Number(val)) / 1.0e+9 + "B" // Six Zeroes for Millions : Math.abs(Number(val)) >= 1.0e+6 ? Math.abs(Number(val)) / 1.0e+6 + "M" // Three Zeroes for Thousands : Math.abs(Number(val)) >= 1.0e+3 ? Math.abs(Number(val)) / 1.0e+3 + "K" : Math.abs(Number(val)); } }); In HTML: {{someval | bigNumRound}}Disfranchise
Thanks Paul. It helped me.. I am adding a fiddle which may help others to see its working. jsfiddle.net/ykng4tkLKarimakarin
No ternary: function MoneyFormat(labelValue) { // Nine Zeroes for Billions if (Math.abs(Number(labelValue)) >= 1.0e+9) { return `R$ ${Math.trunc(Math.abs(Number(labelValue)) / 1.0e+9)}B`; } // Six Zeroes for Millions if (Math.abs(Number(labelValue)) >= 1.0e+6) { return `R$ ${Math.trunc(Math.abs(Number(labelValue)) / 1.0e+6)}M`; } // Three Zeroes for Thousands if (Math.abs(Number(labelValue)) >= 1.0e+3) { return `R$ ${Math.trunc(Math.abs(Number(labelValue)) / 1.0e+3)}K`; } return Math.abs(Number(labelValue)); }Leukemia
U
9

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')
Usufruct answered 16/6, 2015 at 10:20 Comment(1)
This my friends, is the real answerExpropriate
W
7
var lazyround = function (num) {
    var parts = num.split(",");
    return parts.length > 1 ? (Math.round(parseInt(parts.join(""), 10) / Math.pow(1000, parts.length-1)) + " " + ["thousand", "million", "billion"][parts.length-2]) : parts[0];
};

alert(lazyround("9,012,345,678"));
alert(lazyround("12,345,678"));
alert(lazyround("345,678"));
alert(lazyround("678"));

it outputs this:

9 billion
12 million
346 thousand
678

have fun. this works fine and since i dont see that you did anything yourself this is obfuscated.

there you have a working example in jsfiddle: jsfiddle.net/p8pfB/

Wooded answered 15/10, 2012 at 17:13 Comment(0)
M
3

@Paul's answer is great, but it gives 773.282600918 M etc.

We probably dont want it for big numbers. Fixed using Math.round()

function moolah_round(num,locale='en') {
    // Nine Zeroes for Billions
    return Math.abs(Number(num)) >= 1.0e+9
        ? Math.round(Math.abs(Number(num)) / 1.0e+9 ) + " B"
        // Six Zeroes for Millions
        : Math.abs(Number(num)) >= 1.0e+6
            ? Math.round(Math.abs(Number(num)) / 1.0e+6 ) + " M"
            // Three Zeroes for Thousands
            : Math.abs(Number(num)) >= 1.0e+3
                ? Math.round(Math.abs(Number(num)) / 1.0e+3 ) + " K"
                : Math.abs(Number(num)); 
}
Marmion answered 26/8, 2017 at 15:42 Comment(2)
This is alot better... would be nice to be able to choose how many 'decimals' Like instead of 12m it would be nice to have 12.1m or istead of 12k it would be nice to have 12.1k etc etcInexactitude
@iiiml0sto1 I made some changes to this great example just to handle also decimals whenever necessary. See: https://mcmap.net/q/1116468/-how-do-i-round-millions-and-thousands-in-javascriptCressler
T
1
var number = 1345;
var zeroCount = 3;
var roundedNumber = Math.round( number / Math.pow(10,zeroCount) )

Just adjust the zeroCount to the 3 for thousands, 6 for millions, etc. I'm assuming you can use if statements and just need some help with the math functions.

Travancore answered 15/10, 2012 at 17:2 Comment(0)
I
1

Paul Sweatte's answer is good

Deepak Thomas's answer is nice

My answer is way more flexible/customizable and easier to read, so here goes:

Code

function NumbFormat(options) {

  let number = Math.abs(Number(options.number));

  // Nine zeros for Billions
  if (Number(number) >= 1.0e+9) {
    return (number / 1.0e+9).toFixed(options.billion.decimal) + ` ${options.billion.unit}`;
  }

  // Six zeros for Millions
  if (Number(number) >= 1.0e+6) {
    return (number / 1.0e+6).toFixed(options.million.decimal) + ` ${options.million.unit}`;
  }

  // Thrhee zeros for Thousands
  if (Number(number) >= 1.0e+3) {
    return (number / 1.0e+3).toFixed(options.thousand.decimal) + ` ${options.thousand.unit}`;
  }

  return number;
}

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 1,
    'unit': 'M',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 1,
    'unit': 'Million',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 0,
    'unit': 'Million',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

console.log(NumbFormat({
  'number': 100000000,
  'billion': {
    'decimal': 1,
    'unit': 'B',
  },
  'million': {
    'decimal': 0,
    'unit': 'M',
  },
  'thousand': {
    'decimal': 1,
    'unit': 'K',
  },
}));

With the above code you are in control of how many decimals you want for billions, millions or thousands, you are also in control of which unit you wish to display :)

Inexactitude answered 19/2, 2020 at 16:33 Comment(0)
C
1

This is an improvement over Deepak Thomas's answer.

It handles decimals whenever it's necessary and gives more readability and control over the function.

Run the code snippet to see a 5 alert live demo showing its usage.

function numRound(num) {
  num = Math.abs(Number(num))
  const billions = num/1.0e+9
  const millions = num/1.0e+6
  const thousands = num/1.0e+3
  return num >= 1.0e+9 && billions >= 100  ? Math.round(billions)  + "B"
       : num >= 1.0e+9 && billions >= 10   ? billions.toFixed(1)   + "B"
       : num >= 1.0e+9                     ? billions.toFixed(2)   + "B"
       : num >= 1.0e+6 && millions >= 100  ? Math.round(millions)  + "M"
       : num >= 1.0e+6 && millions >= 10   ? millions.toFixed(1)   + "M"
       : num >= 1.0e+6                     ? millions.toFixed(2)   + "M"
       : num >= 1.0e+3 && thousands >= 100 ? Math.round(thousands) + "K"
       : num >= 1.0e+3 && thousands >= 10  ? thousands.toFixed(1)  + "K"
       : num >= 1.0e+3                     ? thousands.toFixed(2)  + "K"
       : num.toFixed()
}

alert(numRound(1234))
alert(numRound(23456))
alert(numRound(345678))
alert(numRound(4567890))
alert(numRound(56789012))
Cressler answered 6/7, 2021 at 15:54 Comment(0)
N
1

the simplest way to achieve this is to use Intl api.

example:

const formatter = Intl.NumberFormat('en', {notation: 'compact'})

const K = formatter.format(1555) // thousand
const M = formatter.format(1555555) // million
const B = formatter.format(1555555555) // billion
const T = formatter.format(1555555555555) // trillion

console.log(K, M, B, T)
Night answered 18/10, 2022 at 14:27 Comment(0)
E
1

I modified cetinajero's and Deepak Thomas's awesome answers to also handle negative numbers. (and not use ternaries)

const numRound = (number) => {
  let num = number;
  num = Number(num);
  const billions = num / 1.0e9;
  const millions = num / 1.0e6;
  const thousands = num / 1.0e3;
  if (Math.abs(num) >= 1.0e9 && Math.abs(billions) >= 100) {
    return `${Math.round(billions)}B`
  }
  if (Math.abs(num) >= 1.0e9 && Math.abs(billions) >= 10) {
    return `${billions.toFixed(1)}B`
  }
  if (Math.abs(num) >= 1.0e9) {
    return `${billions.toFixed(2)}B`
  }
  if (Math.abs(num) >= 1.0e6 && Math.abs(millions) >= 100) {
    return `${Math.round(millions)}M`
  }
  if (Math.abs(num) >= 1.0e6 && Math.abs(millions) >= 10) {
    return `${millions.toFixed(1)}M`
  }
  if (Math.abs(num) >= 1.0e6) {
    return `${millions.toFixed(2)}M`
  }
  if (Math.abs(num) >= 1.0e3 && Math.abs(thousands) >= 100) {
    return `${Math.round(thousands)}K`
  }
  if (num >= 1.0e3 && thousands >= 10) {
    return `${thousands.toFixed(1)}K`
  }
  if (Math.abs(num) >= 1.0e3) {
    return `${thousands.toFixed(1)}K`
  }
  return num.toFixed();
};

console.log(numRound(-23400006))
console.log(numRound(1200))
console.log(numRound(654321))
console.log(numRound(12334000060))
Erythrocyte answered 17/11, 2022 at 14:48 Comment(0)
M
0

Use str.length and the switch case

var number=12345;

something like this

switch (number.length) {
  case 4:
    alert(number/10000+"Thousand");
    break;

}
Mylan answered 15/10, 2012 at 16:55 Comment(1)
in this case i think so since it looks like the creator of this question has tried nothing to achieve this.Wooded

© 2022 - 2024 — McMap. All rights reserved.