Javascript Number Type format

Description

Javascript Number Type format


function formatNumber (num, decplaces) {
    // convert in case it arrives as a string value
    num = parseFloat(num);/*from w  ww.ja  v a  2 s.  com*/
    // make sure it passes conversion
    if (!isNaN(num)) {

        var str = "" + Math.round (eval(num) * Math.pow(10,decplaces));
        // exponent means value is too big or small for this routine
        if (str.indexOf("e") != -1) {
            return "Out of Range";
        }
        // if needed for small values, pad zeros
        // to the left of the number
        while (str.length <= decplaces) {
            str = "0" + str;
        }
        // calculate decimal point position
        var decpoint = str.length - decplaces;

        return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
    } else {
        return "NaN";
    }
}
console.log(formatNumber(123123.9876, 2));
console.log(formatNumber(123123.123123, 2));



PreviousNext

Related