本文實(shí)例講述了js實(shí)現(xiàn)的格式化數(shù)字和金額功能。分享給大家供大家參考,具體如下:
格式化數(shù)字,格式化金額:
function number_format(number, decimals, dec_point, thousands_sep) { /* * 參數(shù)說(shuō)明: * number:要格式化的數(shù)字 * decimals:保留幾位小數(shù) * dec_point:小數(shù)點(diǎn)符號(hào) * thousands_sep:千分位符號(hào) * */ number = (number + '').replace(/[^0-9+-Ee.]/g, ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point, s = '', toFixedFix = function (n, prec) { var k = Math.pow(10, prec); return '' + Math.ceil(n * k) / k; }; s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); var re = /(-?/d+)(/d{3})/; while (re.test(s[0])) { s[0] = s[0].replace(re, "$1" + sep + "$2"); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec);}如何使用:
var num=number_format(1234567.089, 2, ".", ",");//1,234,567.09console.log(num);
再來(lái)一個(gè),直接舍去的辦法:
function number_format(number, decimals, dec_point, thousands_sep) { /* * 參數(shù)說(shuō)明: * number:要格式化的數(shù)字 * decimals:保留幾位小數(shù) * dec_point:小數(shù)點(diǎn)符號(hào) * thousands_sep:千分位符號(hào) * */ number = (number + '').replace(/[^0-9+-Ee.]/g, ''); var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point, s = '', toFixedFix = function (n, prec) { var k = Math.pow(10, prec); return '' + Math.floor(n * k) / k; }; s = (prec ? toFixedFix(n, prec) : '' + Math.floor(n)).split('.'); var re = /(-?/d+)(/d{3})/; console.log(s) while (re.test(s[0])) { s[0] = s[0].replace(re, "$1" + sep + "$2"); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec);}var num=number_format(1234567.089, 2, ".", ",");//1,234,567.08console.log(num)感興趣的朋友可以使用在線HTML/CSS/JavaScript代碼運(yùn)行工具http://tools.VeVB.COm/code/HtmlJsRun測(cè)試上述代碼運(yùn)行結(jié)果。
PS:這里再為大家推薦幾款計(jì)算工具供大家進(jìn)一步參考借鑒:
在線一元函數(shù)(方程)求解計(jì)算工具:
http://tools.VeVB.COm/jisuanqi/equ_jisuanqi
科學(xué)計(jì)算器在線使用_高級(jí)計(jì)算器在線計(jì)算:
http://tools.VeVB.COm/jisuanqi/jsqkexue
在線計(jì)算器_標(biāo)準(zhǔn)計(jì)算器:
http://tools.VeVB.COm/jisuanqi/jsq
更多關(guān)于JavaScript相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《JavaScript數(shù)學(xué)運(yùn)算用法總結(jié)》、《JavaScript數(shù)據(jù)結(jié)構(gòu)與算法技巧總結(jié)》、《JavaScript數(shù)組操作技巧總結(jié)》、《JavaScript排序算法總結(jié)》、《JavaScript遍歷算法與技巧總結(jié)》、《JavaScript查找算法技巧總結(jié)》及《JavaScript錯(cuò)誤與調(diào)試技巧總結(jié)》
希望本文所述對(duì)大家JavaScript程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注