HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptModerate

Function that abbreviates a number (e.g. 1202 => 1.2K)

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
number1202functionabbreviatesthat

Problem

Like Twitter and Instagram and others I wanted to display numbers like 1.2K and 3.8M etc. My function works well enough but I would appreciate any input you may have.

function abbrNum (num) {
    if(typeof num !== 'number') {
        throw new TypeError('Expected a number');
    }

    var shortNumber;
    var exponent;
    var suffixes = ['K', 'M', 'B', 'T'];
    var size = (num + '').length;

    exponent = size % 3 === 0 ? size - 3 : size - (size % 3);

    if(num < 1000) {
        return num;
    } else {
        shortNumber = Math.round(10 * (num / Math.pow(10, exponent))) / 10;
    }

    if(exponent < 6) {
        shortNumber += suffixes[0];
    } else if(exponent < 9) {
        shortNumber += suffixes[1];
    } else if(exponent < 12) {
        shortNumber += suffixes[2];
    } else if(exponent < 16) {
        shortNumber += suffixes[3];
    }

    return shortNumber;
}


Update: This code (updated according to feedback) is available on npm.

Solution

converting to string just to get the length won't work if there is a decimal or it's large enough that the string conversion uses scientific notation.

var size = floor(log(num)/log(10))+1;


This will give the place of the highest significant digit (1 to 9 results in 1, 10 to 99 results in 2, 100 to 999 results in 3, etc...)

Code Snippets

var size = floor(log(num)/log(10))+1;

Context

StackExchange Code Review Q#100584, answer score: 18

Revisions (0)

No revisions yet.