formatting ideas

by Ryan

JavaScript

var _methods = {
    numberFormat : function(toFormat, prefix, postfix, decimals){
        if(typeof toFormat === undefined) toFormat = 0;
        if(typeof decimals === undefined || decimals < 0) decimals = 0;
        if(typeof prefix === undefined) prefix = "";
        if(typeof postfix === undefined) postfix = "";
        
        var toReturn;
        if(decimals === 0){
            toReturn = toFormat.toFixed(0).replace(/(\d)(?=(\d{3})+$)/g, "$1,")
        } else {
            toReturn = toFormat.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
        }
        
        return prefix + toReturn + postfix;
    },
    usDollar : function(toFormat){
        return _methods.numberFormat(toFormat, "$", "", 2);
    },
    integer : function(toFormat){
        return _methods.numberFormat(toFormat, "", "", 0);
    },
    percent : function(toFormat){
        if( typeof toFormat === undefined){
            toFormat = 0;
        } else if(typeof toFormat === "string"){
            toFormat = parseFloat(toFormat);
        }
        return _methods.numberFormat(toFormat * 100, "", "%", 2);
    }
};

console.log(_methods.usDollar(50));
console.log(_methods.usDollar(500));
console.log(_methods.usDollar(5000));
console.log(_methods.usDollar(500000));
console.log(_methods.usDollar(5000000000));
console.log(_methods.usDollar(50000000000000.21));
console.log(_methods.usDollar(50000000000000.2163));

console.log(_methods.percent(0.01));
console.log(_methods.percent(0.82321));
console.log(_methods.percent(0.0001));

console.log(_methods.integer(1));
console.log(_methods.integer(1.123));
console.log(_methods.integer(0.0001));
console.log(_methods.integer(11231231421234123));