js j将数字每三位用逗号隔开的方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>数字每隔三位逗号隔开</title> </head> <style type="text/css"> .text{ width: 300px; height: 40px;border: 1px solid #ccc; color: #000;font-size: 16px;line-height: 40px;font-weight:bold; } </style> <body> <div class="one"> <h3>方法1</h3> <input class="one_input" value="100043241231.6"> <input class="one_btn" type="button" value="提交" onclick="numbers.one()"> <div class="one_text text">...</div> </div> <div class="two"> <h3>方法2</h3> <input class="two_input" value="178943241231.5"> <input class="two_btn" type="button" value="提交" onclick="numbers.two()"> <div class="two_text text">...</div> </div> <div class="three"> <h3>方法3</h3> <input class="three_input" value="12223241231.126"> <input class="three_btn" type="button" value="提交" onclick="numbers.three()"> <div class="three_text text">...</div> </div> </body> <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script> <script type="text/javascript"> var numbers = { one : function(){ var oneval = $(".one_input").val(); $(".one_text").html(parseFloat(oneval).toLocaleString()); }, two : function(){ var twoval = $(".two_input").val(); $(".two_text").html(fun.format_number1(twoval)); }, three : function(){ var threeval = $(".three_input").val(); $(".three_text").html(fun.format_number1(threeval)); } } var fun = { format_number1 : function(n){ var b=parseInt(n).toString(); var len=b.length; if(len<=3){return b;} var r=len%3; return r>0?b.slice(0,r)+","+b.slice(r,len).match(/\d{3}/g).join(","):b.slice(r,len).match(/\d{3}/g).join(","); }, format_number2 : function(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"; //自动补小数点后两位 console.log(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); console.log(str) } } } </script> </html>