Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Abbreviate large numbers in Javascript
// Iterated from: https://stackoverflow.com/questions/10599933/convert-long-number-into-abbreviated-string-in-javascript-with-a-special-shortn
function abbreviateNumber(value) {
let newValue = value;
const suffixes = ["", "K", "M", "B","T"];
let suffixNum = 0;
while (newValue >= 1000) {
newValue /= 1000;
suffixNum++;
}
newValue = newValue.toPrecision(3);
newValue += suffixes[suffixNum];
return newValue;
}
@KickButtowski80
Copy link

KickButtowski80 commented Aug 12, 2020

crystal clear answer thank you

@azivkovi
Copy link

azivkovi commented Nov 20, 2020

Thanks!

@sarabisohrab
Copy link

sarabisohrab commented Mar 26, 2021

Simple and Perfect answer! Thanks!

@warbon
Copy link

warbon commented Sep 30, 2021

Thanks nice one.

@OsamaHayyan
Copy link

OsamaHayyan commented Oct 31, 2021

if number is 12 then it be 12.0
or 1 it will be 1.0

you can change it to:
newValue = newValue.toString().length > 2 ? newValue.toPrecision(3) : newValue.toPrecision();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment