javascript - Easier way to calculate numeric multiplier suffix -
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 @ point i'm going going upwards power of hundreds, there easier way this?
function formatnumber(number) { var = 0; units = [ "", "k", "m", "b", "t" ]; // etc while (number > 1000) { number /= 1000; += 1; } return math.floor(number * 1000) / 1000 + units[i]; } formatnumber(1234567); // 1.234m formatnumber(1230567); // 1.23m
this might faster large numbers:
function formatnumber(number) { var i; units = [ "", "k", "m", "b", "t" ]; // etc = math.round(math.log(number) / math.log(10) / 3); number /= math.pow(10, * 3); return math.floor(number * 1000) / 1000 + units[i]; } formatnumber(1234567); // 1.234m formatnumber(1230567); // 1.23m
Comments
Post a Comment