Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Mar 27, 2015

Format Numbers in Millions and Thousands

Here is simple and esay to use javaScript function which formats numbers to M and K and also adds brackets to negative numbers. Very handy and easu to use function to nicley fomat numbers on your webpage.


function formatNumbers(_num, _round) {
    var isNegative = false;
    var num = Number(_num);
    var suffix = "";
    var numOut;
    if (num < 0)
        isNegative = true;

    num = Math.abs(num);

    if (num > 1000000) {
        suffix = " M";
        num = Math.round(num / 1000000, _round);
    }
    else if (num > 10000) {
        suffix = " K";
        num = Math.round(num / 1000, _round);

    }
    else {
        num = Math.round(num, _round);
        suffix = "";
    }

    /************* Add brackets to negative numbers ***************/
    if (isNegative) {
        numOut = "(" + num + ")";
    }
    else
    {
        numOut = num;
    }

    numOut += suffix;
    return numOut;

}



This can be easily customized according to your need with out using any heavy library file