這個程式碎片算是將數字每隔三位加上逗號的延伸寫作了,不過這次重點放在Javascript上的寫法了。如何將12356.25變成金額表示法(NT$12,356.25)呢?程式碼如下:

function money_format(value,fixed,currency){
	var fixed = fixed || 0;
	var currency = currency || '';
	isNaN(parseFloat(value))? value=0 : value=parseFloat(value);
	v = value.toFixed(fixed).toString();
	var ps = v.split('.');
	var whole = ps[0];
	var sub = ps[1] ? '.' + ps[1] : '';
	var r = /(\d+)(\d{3})/;
	while (r.test(whole)) {
		whole = whole.replace(r, '$1' + ',' + '$2');
	}
	v = whole + sub;
	if (v.charAt(0) == '-') {
		return currency + '-' + '$' + v.substr(1);
	}
	return currency + '$' +v;
}
/************
 *  測試函式
 ************/
//使用數字型態或字串型態傳入皆可
money = money_format(-333224);  //輸出$-333,224
money = money_format('-333224');//輸出$-333,224
//指定小數位數
money = money_format(333224,2);    //輸出$333,224.00
money = money_format('333224.2',3);//輸出$333,224.200
//指定幣別
money = money_format(333224,2,'US');//輸出US$333,224.00
money = money_format(333224,0,'NT');//輸出NT$333,224
arrow
arrow
    全站熱搜

    低溫烘培 發表在 痞客邦 留言(0) 人氣()