zoukankan      html  css  js  c++  java
  • js中货币格式化两种方法

    直接在Number中扩展货币格式方法

    Number.prototype.formatMoney = function (places, symbol, thousand, decimal) {
    		        places = !isNaN(places = Math.abs(places)) ? places : 2;
    		        symbol = symbol !== undefined ? symbol : "$";
    		        thousand = thousand || ",";
    		        decimal = decimal || ".";
    		        var number = this,
    		            negative = number < 0 ? "-" : "",
    		            i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
    		            j = (j = i.length) > 3 ? j % 3 : 0;
    		        return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(d{3})(?=d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    		    };
    		    //参数:保留几位小数,货币符号,千位分隔符,小数分隔符
    		    var a=2345.0000.formatMoney(2,'',',','.');
    		    console.log(a);
    

    货币格式化方法,不用prototype对Number进行拓展的版本

    function formatMoney(number, places, symbol, thousand, decimal) {
    				number = number || 0;
    				places = !isNaN(places = Math.abs(places)) ? places : 2;
    				symbol = symbol !== undefined ? symbol : "$";
    				thousand = thousand || ",";
    				decimal = decimal || ".";
    				var negative = number < 0 ? "-" : "",
    					i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + "",
    					j = (j = i.length) > 3 ? j % 3 : 0;
    				return symbol + negative + (j ? i.substr(0, j) + thousand : "") + i.substr(j).replace(/(d{3})(?=d)/g, "$1" + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : "");
    			}
    			console.log(formatMoney(54321)) // $54,321
    
    
  • 相关阅读:
    307. Range Sum Query
    OLI 课程 & Java入学考试的五道题
    745. Prefix and Suffix Search 查找最大index的单词
    38.Count and Say 报数
    721. Accounts Merge合并电子邮件账户
    265. Paint House II 房子涂色K种选择的版本
    【转】如何做人性化的代码审查?从高到低、用例子
    java之struts2之文件下载
    java之struts2之文件上传
    java之struts2之拦截器
  • 原文地址:https://www.cnblogs.com/sakura-sakura/p/6678277.html
Copyright © 2011-2022 走看看