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>
cssfirefly http://cssfirefly.cnblogs.com
原文地址:https://www.cnblogs.com/cssfirefly/p/3582027.html