Last active
November 12, 2020 20:46
-
-
Save nhalstead/0ab077ff8af298122ac81a49ebf7c5ec to your computer and use it in GitHub Desktop.
Javascript Number Abreavtion
This file contains 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
/** | |
* Parse an aberration of a number | |
* | |
* @author Noah Halstead <nhalstead00@gmail.com> | |
* @param {string} value Abbreviated Number | |
* @return {number} amount | |
*/ | |
function unabbreviateNumber(value = "") { | |
value = value.toLowerCase().replace(/,/g, "") | |
const reg = /([0-9\.]+)(k|m|b|t|q|)/i; | |
if ((m = reg.exec(value)) !== null) { | |
let num = parseFloat(m[1]); | |
switch(m[2]) { | |
case "": break; | |
case "k": | |
num = num * (10 ** 3); | |
break; | |
case "m": | |
num = num * (10 ** 6); | |
break; | |
case "b": | |
num = num * (10 ** 9); | |
break; | |
case "t": | |
num = num * (10 ** 12); | |
break; | |
case "q": | |
num = num * (10 ** 15); | |
break; | |
} | |
return num; | |
} | |
return 0; | |
} | |
/** | |
* Convert a number into an Abbreated Number | |
* | |
* @link https://stackoverflow.com/a/10601315/5779200 | |
* @param {number} amount | |
* @return {string} Abbreated Number | |
*/ | |
function abbreviateNumber(value) { | |
var newValue = value; | |
if (value >= 1000) { | |
var suffixes = ["", "k", "m", "b","t"]; | |
var suffixNum = Math.floor( (""+value).length/3 ); | |
var shortValue = ''; | |
for (var precision = 2; precision >= 1; precision--) { | |
shortValue = parseFloat( (suffixNum != 0 ? (value / Math.pow(1000,suffixNum) ) : value).toPrecision(precision)); | |
var dotLessShortValue = (shortValue + '').replace(/[^a-zA-Z 0-9]+/g,''); | |
if (dotLessShortValue.length <= 2) { break; } | |
} | |
if (shortValue % 1 != 0) shortValue = shortValue.toFixed(1); | |
newValue = shortValue+suffixes[suffixNum]; | |
} | |
return newValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment