Last active
April 10, 2021 23:11
-
-
Save etaubman/7294219 to your computer and use it in GitHub Desktop.
Shorten Numbers Using Javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function shortenNumber(n, d) { | |
if (n < 1) return "<1"; | |
var k = n = Math.floor(n); | |
if (n < 1000) return (n.toString().split("."))[0]; | |
if (d !== 0) d = d || 1; | |
function shorten(a, b, c) { | |
var d = a.toString().split("."); | |
if (!d[1] || b === 0) { | |
return d[0] + c | |
} else { | |
return d[0] + "." + d[1].substring(0, b) + c; | |
} | |
} | |
k = n / 1e15; if (k >= 1) return shorten(k, d, "Q"); | |
k = n / 1e12; if (k >= 1) return shorten(k, d, "T"); | |
k = n / 1e9; if (k >= 1) return shorten(k, d, "B"); | |
k = n / 1e6; if (k >= 1) return shorten(k, d, "M"); | |
k = n / 1e3; if (k >= 1) return shorten(k, d, "K"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment