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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM