A simpler way to calculate a numerical multiplier
function num(n) {
if (n >= 1000 && n < 10000) return (n/1000).toFixed(3) + "K";
if (n >= 10000 && n < 100000) return (n/1000).toFixed(1) + "K";
if (n >= 100000 && n < 1000000) return (n/1000).toFixed(0) + "K";
if (n >= 1000000 && n < 10000000) return (n/1000000).toFixed(3) + "M";
if (n >= 10000000 && n < 100000000) return (n/1000000).toFixed(1) + "M";
if (n >= 100000000 && n < 1000000000) return (n/1000000).toFixed(0) + "M";
if (n >= 1000000000 && n < 10000000000) return (n/1000000000).toFixed(3) + "B";
if (n >= 10000000000 && n < 100000000000) return (n/1000000000).toFixed(1) + "B";
if (n >= 100000000000 && n < 1000000000000) return (n/1000000000).toFixed(0) + "B";
if (n >= 1000000000000 && n < 10000000000000) return (n/1000000000000).toFixed(3) + "T";
if (n >= 10000000000000 && n < 100000000000000) return (n/1000000000000).toFixed(1) + "T";
if (n >= 100000000000000 && n < 1000000000000000) return (n/1000000000000).toFixed(0) + "T";
return n;
}
Since at some point Iβm probably going to rise to the power of hundreds, is there an easier way to do this?
function formatNumber(number) {
var i = 0; units = [ "", "K", "M", "B", "T" ]; // etc
while (number > 1000) {
number /= 1000;
i += 1;
}
return Math.floor(number * 1000) / 1000 + units[i];
}
formatNumber(1234567); // 1.234M
formatNumber(1230567); // 1.23M
This can be faster for very large numbers:
function formatNumber(number) {
var i; units = [ "", "K", "M", "B", "T" ]; // etc
i = Math.round(Math.log(number) / Math.log(10) / 3);
number /= Math.pow(10, i * 3);
return Math.floor(number * 1000) / 1000 + units[i];
}
formatNumber(1234567); // 1.234M
formatNumber(1230567); // 1.23M
Halcyon.
function fnum(number) {
var i, x, units = [ "", "K", "M", "B", "T", "Qa", "Qi", "Sx", "Sp", "Oc", "No", "Dc" ];
i = Math.floor(Math.log(number) / Math.log(10) / 3);
x = Math.floor(Math.log(number) / Math.log(10)) % 3;
number /= Math.pow(10, i * 3);
return ((number * 1000) / 1000).toFixed(77 % ((x * 2) + 3)) + units[i];
}
0 999 2 1 10 0 100 , . .
fnum(22000); >> 22.00K
fnum(153000000); >> 153M
fnum(2,230,000,000,000); >> 2.23T