Based on my answer to https://stackoverflow.com/a/126646/212 , your answer is actually a bit shorter to implement using .substring(0,3) :
function format(n) { with (Math) { var base = floor(log(abs(n))/log(1000)); var suffix = 'kmb'[base-1]; return suffix ? String(n/pow(1000,base)).substring(0,3)+suffix : ''+n; } }
(As usual, do not use Math unless you know exactly what you are doing, assigning var pow=... and the like will lead to crazy errors. See the link for a safer way to do this.)
> tests = [-1001, -1, 0, 1, 2.5, 999, 1234, 1234.5, 1000001, Math.pow(10,9), Math.pow(10,12)] > tests.forEach(function(x){ console.log(x,format(x)) }) -1001 "-1.k" -1 "-1" 0 "0" 1 "1" 2.5 "2.5" 999 "999" 1234 "1.2k" 1234.5 "1.2k" 1000001 "1.0m" 1000000000 "1b" 1000000000000 "1000000000000"
You need to catch the case where the result is = 1 trillion, if your requirement for 3 characters is strict, otherwise you risk creating corrupted data, which would be very bad.
ninjagecko May 15 '12 at 12:27 2012-05-15 12:27
source share