javascript related formatting

javascript related formatting

1. Format money (positive number)

/**
 * 格式化金钱
 * 
 * @param str
 * @returns {String}
 */
function formatMoney(str) {
    var str = String(str);
    var newStr = "";
    var count = 0;

    if (str.indexOf(".") == -1) {
        for (var i = str.length - 1; i >= 0; i--) {
            if (count % 3 == 0 && count != 0) {
                newStr = str.charAt(i) + "," + newStr;
            } else {
                newStr = str.charAt(i) + newStr;
            }
            count++;
        }
        str = newStr + ".00"; // 自动补小数点后两位
    } else {
        for (var i = str.indexOf(".") - 1; i >= 0; i--) {
            if (count % 3 == 0 && count != 0) {
                newStr = str.charAt(i) + "," + newStr;
            } else {
                newStr = str.charAt(i) + newStr; // 逐个字符相接起来
            }
            count++;
        }
        str = newStr + (str + "00").substr((str + "00").indexOf("."), 3);
    }
    return str;
}

2. Format money (including negative numbers)

/**
 * 将数值四舍五入(保留2位小数)后格式化成金额形式
 * 包含对于负数的操作
 * @param num 数值(Number或者String)
 * @return 金额格式的字符串,如'1,234,567.45'
 * @type String
 */
function formatMoneyNew(num) {
    var result = num;
    if (num < 0){
        num = 0 - num;
    }
    if (/[^0-9\.]/.test(num)){
        return "0.00";
    }
    if (num == null || num == "null" || num == ""||isNaN(num)){
        return "0.00";
    }
    num = new Number(num).toFixed(2);
    num = num.toString().replace(/^(\d*)$/, "$1.");
    num = (num + "00").replace(/(\d*\.\d\d)\d*/, "$1");
    num = num.replace(".", ",");
    var re = /(\d)(\d{
   
   3},)/;
    while (re.test(num)){
        num = num.replace(re, "$1,$2");
    }
    num = num.replace(/,(\d\d)$/, ".$1");
    if (result < 0){
        result = "-" + num ;
    } else {
        result = num;
    }
    return result;

}

3. Format the date

/**
 * 格式化日期 js把字符串(yyyymmdd)转换成日期格式(yyyy-mm-dd)
 */
function formatDate(str){
    if(str != null && str != undefined && str != '' && str != 'null'){
        return str.replace(/^(\d{
   
   4})(\d{
   
   2})(\d{
   
   2})$/, "$1-$2-$3");
    } else {
        return "";
    }
}

4. Format the data

/**
 * 格式化数据 字符串内容为空转化成""
 */
function formatValue(str){
    if(str != null && str != undefined && str != '' && str != 'null'){
        return str;
    } else {
        return "";
    }
}

Guess you like

Origin blog.csdn.net/ampsycho/article/details/77750275