格式化 货币 时间

//格式化货币
exports.formatMoney = function(s){
    if(s == "undefined" || s == null ) return "0.00";
    s = (s+"").replace(",","");
    if(/[^0-9\.]/.test(s)) return "格式错误";
    s=s.replace(/^(\d*)$/,"$1.");
    s=(s+"00").replace(/(\d*\.\d\d)\d*/,"$1");
    s=s.replace(".",",");
    var re=/(\d)(\d{3},)/;
    while(re.test(s))
            s=s.replace(re,"$1,$2");
    s=s.replace(/,(\d\d)$/,".$1");
    //return "¥" + s.replace(/^\./,"0.")
    return s.replace(/^\./,"0.")
}
// 时间格式化 如:formatDate("2010-04-30", "yyyy-MM-dd HH:mm:ss.fff")

exports.formatDate = function(date, format) { 
    if (!date) return "";   
    if (!format) format = "yyyy-MM-dd HH:mm:ss";   
    switch(typeof date) { 
        case "string":   
            date = new Date(date.replace(/-/g, "/"));   
            break;   
        case "number":   
            date = new Date(date);
            break;   
    }    
    if (!date instanceof Date) return "";   
    var dict = {   
        "yyyy": date.getFullYear(),   
        "M": date.getMonth() + 1,   
        "d": date.getDate(),   
        "H": date.getHours(),   
        "m": date.getMinutes(),   
        "s": date.getSeconds(),   
        "MM": ("" + (date.getMonth() + 101)).substr(1),   
        "dd": ("" + (date.getDate() + 100)).substr(1),   
        "HH": ("" + (date.getHours() + 100)).substr(1),   
        "mm": ("" + (date.getMinutes() + 100)).substr(1),   
        "ss": ("" + (date.getSeconds() + 100)).substr(1),
        "fff": ("" + (date.getMilliseconds() + 1000)).substr(1)
    };       
    return format.replace(/(yyyy|MM?|dd?|HH?|ss?|mm?|fff?)/g, function() {   
        return dict[arguments[0]];   
    });                   
} 
//保留数字小数点后两位 不作四舍五入
exports.fNum = function(val){
    var arr_=val.toString().split('.');    
    if(arr_.length<2){
        return val;    
    }else if(arr_[1].length<3){
        return val;    
    }else{
        return [arr_[0],arr_[1].substring(0,2)].join('.');
    }
}

 

posted @ 2016-05-17 16:25  觉信  阅读(150)  评论(0编辑  收藏  举报