js 實現千分數分割(1000,分割後的結果為1,000)

來源:互聯網
上載者:User
問題:客戶輸入1000,自動就分1,000,邊輸入邊分割.

邊輸入變分割好辦 直接使用onkeyup 觸發我們的function就可以了,分割比較麻煩
我寫的代碼如下:
<script language="JavaScript">
    function toFormant(obj)
    {
       
        var numstr = obj.value;       
        var num =numstr.replace(/,| /g,"");
        if(num.length>1)
        {
            num = num.replace(/\b[0*]/g,"");
        }       
        if(!num.match(/[^0-9]/g))
        {
            //alert(num);
            var a = new Array();
            if(num.length>3)
            {
                for(i=num.length;i>0;i=i-3)
                {
                    a.push(num.substring(i-3,i));
                }
                obj.value=a.reverse().join(",");
            }
            else
            {
                obj.value = num.replace(/,/g,"");
            }
        }
        else
        {
            alert("NOT A No.");
        }
    }
  </script>

論壇裡面的一個大牛的代碼如下:
<script language="javascript">
        function show(obj)
        {
            obj.value=obj.value.replace(/,/g,"")
            if(/^[1-9]\d*$/.test(obj.value))
            obj.value = obj.value.replace(/(?=(?!\b)(?:\d{3})+(?!\d))/g,',');
        }
</script>
哎,還是很有差距的啊,繼續努力吧,記錄+自勉下

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.