javascript 金额格式化
金额格式化
example:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script> 5 </head> 6 <body> 7 Hello<br> 8 <script> 9 // format money: x,xxx.xx 10 function moneyFormat(money, digit) { 11 digit = digit > 0 && digit <= 20 ? digit : 2; 12 money = parseFloat(money).toFixed(digit); 13 var integerArr = money.split(".")[0].split("").reverse(); 14 var decimals = money.split(".")[1]; 15 tempArr = ""; 16 for (var i=0,k=integerArr.length;i<k;i++) { 17 var cammaTag = (i+1)%3==0 && (i+1)!=k ? "," : ""; 18 tempArr += integerArr[i] + cammaTag; 19 } 20 money = tempArr.split("").reverse().join("") + "." + decimals; 21 return money; 22 } 23 document.write(moneyFormat(11111.111,-2)+"<br>"); 24 document.write(moneyFormat(22222.222,5)+"<br>"); 25 document.write(moneyFormat(3333333.333,1)+"<br>"); 26 </script> 27 </body> 28 </html>
result: