數字每三位加逗號

weixin_30639719發表於2020-04-05
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 + ".00"; //自動補小數點後兩位 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




轉載於:https://www.cnblogs.com/zouyun/p/9679574.html

相關文章