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
    
    
  • 相关阅读:
    第十六天
    第十五天
    STM8L段式液晶驱动器
    STM8L的LCD接口详解及驱动程序
    作为合格的工程师,这些电路图一辈子都得记住!
    双向晶闸管触发电路工作原理图
    3~15伏10A大电流可调稳压电源
    用TL431制作简单充电器电路
    5V USB充电器电路图
    555
  • 原文地址:https://www.cnblogs.com/sakura-sakura/p/6678277.html
Copyright © 2011-2022 走看看