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
    
    
  • 相关阅读:
    社交类app开发( 仿陌陌 客户端+服务器端)
    iPhone的xib与iPad的xib相互转换
    SVN的搭建
    使用企业证书给iOS应用重签
    [破解版]Unity3d引擎最新稳定版本4.5.5下载(官方最新稳定版本)
    iphone开发资源汇总
    iOS绘图教程
    iOS静态库相关-封装lib
    iOS内存管理策略和实践
    前台中文乱码
  • 原文地址:https://www.cnblogs.com/sakura-sakura/p/6678277.html
Copyright © 2011-2022 走看看