js給數字加三位一逗號間隔的兩種方法(面試題)


方法一:

 

<script  type= "text/javascript">
   //保留三位小數,toLocaleString() 方法可把一個 Number 對象轉換為本地格式的字符串。
    var   num_s = "1232134456.546 ";
    alert(parseFloat(num_s).toLocaleString());

</script>

方法二:

<script type="text/javascript">
// 小數點位不限制
function format_number(nStr ){ nStr += ''; x = nStr.split('.'); x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2'); } return x1 + x2; } var a="53669988.000"; alert(format_number(a)); alert(format_number("wahh")); alert(format_number(0)); alert(format_number(6698.0023)); </script>

 


免責聲明!

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



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