JavaScript 格式化數字 - 轉

來源:互聯網
上載者:User

標籤:type   array   style   四捨五入   tofixed   [1]   小數點   parse   oat   

 1 function number_format(number, decimals, dec_point, thousands_sep,roundtag) { 2     /* 3     * 參數說明: 4     * number:要格式化的數字 5     * decimals:保留幾位小數 6     * dec_point:小數點符號 7     * thousands_sep:千分位符號 8     * roundtag:舍入參數,預設 "ceil" 向上取,"floor"向下取,"round" 四捨五入 9     * */10     number = (number + ‘‘).replace(/[^0-9+-Ee.]/g, ‘‘);11     roundtag = roundtag || "ceil"; //"ceil","floor","round"12     var n = !isFinite(+number) ? 0 : +number,13         prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),14         sep = (typeof thousands_sep === ‘undefined‘) ? ‘,‘ : thousands_sep,15         dec = (typeof dec_point === ‘undefined‘) ? ‘.‘ : dec_point,16         s = ‘‘,17         toFixedFix = function (n, prec) {18  19             var k = Math.pow(10, prec);20             console.log();21  22             return ‘‘ + parseFloat(Math[roundtag](parseFloat((n * k).toFixed(prec*2))).toFixed(prec*2)) / k;23         };24     s = (prec ? toFixedFix(n, prec) : ‘‘ + Math.round(n)).split(‘.‘);25     var re = /(-?\d+)(\d{3})/;26     while (re.test(s[0])) {27         s[0] = s[0].replace(re, "$1" + sep + "$2");28     }29  30     if ((s[1] || ‘‘).length < prec) {31         s[1] = s[1] || ‘‘;32         s[1] += new Array(prec - s[1].length + 1).join(‘0‘);33     }34     return s.join(dec);35 }36 console.log(number_format(2, 2, ".", ","))//"2.00"37 console.log(number_format(3.7, 2, ".", ","))//"3.70"38 console.log(number_format(3, 0, ".", ",")) //"3"39 console.log(number_format(9.0312, 2, ".", ","))//"9.03"40 console.log(number_format(9.00, 2, ".", ","))//"9.00"41 console.log(number_format(39.715001, 2, ".", ",", "floor")) //"39.71"42 console.log(number_format(9.7, 2, ".", ","))//"9.70"43 console.log(number_format(39.7, 2, ".", ","))//"39.70"44 console.log(number_format(9.70001, 2, ".", ","))//"9.71"45 console.log(number_format(39.70001, 2, ".", ","))//"39.71"46 console.log(number_format(9996.03, 2, ".", ","))//"9996.03"47 console.log(number_format(1.797, 3, ".", ",", "floor"))//"1.797"

 

JavaScript 格式化數字 - 轉

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.