Convert long number into abbreviated string in JavaScript, with a special shortness requirement

前端 未结 16 2525
名媛妹妹
名媛妹妹 2020-11-30 22:33

In JavaScript, how would one write a function that converts a given [edit: positive integer] number (below 100 billion) into a 3-letter abbreviation -- where 0-9 an

16条回答
  •  感动是毒
    2020-11-30 22:56

    Based on my answer at https://stackoverflow.com/a/10600491/711085 , your answer is actually slightly shorter to implement, by 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, don't use Math unless you know exactly what you're doing; assigning var pow=... and the like would cause insane bugs. See 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 will need to catch the case where the result is >=1 trillion, if your requirement for 3 chars is strict, else you risk creating corrupt data, which would be very bad.

提交回复
热议问题