天天看點

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