我们都知道 当显示价格时都会有一个格式 比如:¥666,66.00 或者是 $666,66.00
在网上可以搜到好多种方法,我这里就做下笔记,以免以后用到,下面 附上代码:
function formatMoney (number, places, symbol, thousand, decimal){
number = number || 0;
//保留的小位数 可以写成 formatMoney(542986,3) 后面的是保留的小位数,否则默 认保留两位
places = !isNaN(places = Math.abs(places)) ? places : 2;
//symbol表示前面表示的标志是¥ 可以写成 formatMoney(542986,2,"$")
symbol = symbol !== undefined ? symbol : "¥";
//thousand表示每几位用,隔开,是货币标识
thousand = thousand || ",";
//decimal表示小数点
decimal = decimal || ".";
//negative表示如果钱是负数有就显示“-”如果不是负数 就不显示负号
//i表示处理过的纯数字
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) : "");
}
用时直接formatMoney(66666)就可以了,结果: ¥66,666.00;
如果想要保留x位小数就 formatMoney(666666,x);结果:¥66,666.00;(根据x值的设置显示不同的小数位)
如果想要前面用$表示,就formatMoney(666666,x,"$")结果:$66,666.00;(根据x值的设置显示不同的小数位)