數字每三位加逗號的方法(包含小數)


function formatNum(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 ; //自動補小數點后兩位
        return str;
    }
    // 當數字帶有小數
    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;
    }
}

formatNum('13213.24'); //輸出13,213.34
formatNum('132134.2');  //輸出132,134.20
formatNum('132134');  //輸出132,134.00
formatNum('132134.236');  //輸出132,134.23


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM