I've been trying to solve the problem for a few days, and after several approaches I'm not getting anywhere. By testing several numbers, it shown the obviously correct number, but I got a few errors in the status...
export const formatNumber = (n) => {
let number = n;
let suffix = [97, 92];
let ret = "";
//divide number as long as it has 3 digits; counts up the suffix
//count up the second param, until we reach 122 (=z), we reset to 97(=a) and count up the first param
while (number >= 1000) {
number /= 1000;
if (suffix[1] < 122) {
suffix[1]++;
} else {
suffix[0]++;
suffix[1] = 97
}
}
const stringNumber = String(number);
const i = stringNumber.indexOf(".");
//console.log(test)
//check for the point and build the number string; add trailing zeroes if none available
if (i >= 0) {
ret = stringNumber.substring(0,i) + "." + stringNumber.substring(i+1, i+3);
} else {
ret = stringNumber + ".00";
}
switch (suffix[1]) {
case 92: //number is <1_000
if (i >= 0) {
return stringNumber.substring(0, i) + "." + stringNumber.substring(i+1, i+2);
} else {
return stringNumber + ".0";
}
case 93: //number is < 1_000_000
return ret + "K";
case 94: //number is < 1_000_000_000
return ret + "M";
case 95: //number is < 1_000_000_000_000 (billion)
return ret + "B";
case 96: //number is < 1_000_000_000_000_000 (trillion)
return ret + "T";
default: //number is taller than a trillion and we use the suffix (97 = a; 122 = z)
return ret + String.fromCharCode(suffix[0]) + String.fromCharCode(suffix[1]);
}
}