js格式化金額,可選是否帶千分位,可選保留精度,也是網上搜到的,但是使用沒問題
/*
將數值四捨五入後格式化.
@param num 數值(Number或String)
@param cent 要保留的小數位元(Number)
@param isThousand 是否需要千分位0:不需要,1:需要(數值類型);
@return 格式的字串,如'1,234,567.45'
@type String
*/
function formatNumber(num,cent,isThousand){
num = num.toString().replace(/$|,/g,'');
if(isNaN(num)) //檢查傳入數值類型.
num = "0";
if(isNaN(cent))//確保傳入小數位為數值型數值.
cent = 0;
cent = parseInt(cent);
cent = Math.abs(cent);//求出小數位數,確保為正整數.
if(isNaN(isThousand))//確保傳入是否需要千分位為數值類型.
isThousand = 0;
isThousand = parseInt(isThousand);
if(isThousand isThousand = 0;
if(isThousand >=1) //確保傳入的數值只為0或1
isThousand = 1;
sign = (num == (num = Math.abs(num)));//取得符號(正/負數)
//Math.floor:傳回小於等於其數值參數的最大整數
num = Math.floor(num*Math.pow(10,cent) 0.500000000001);//把指定的小數位先轉換成整數.多餘的小數位四捨五入.
cents = num%Math.pow(10,cent); //求出小數位數值.
num = Math.floor(num/Math.pow(10,cent) ).toString();//求出整數位數值.
cents = cents.toString();//把小數位轉換成字串,以便求小數位長度.
while(cents.lengthcents = "0" cents;
}
if(isThousand == 0) //不需要千分位符.
return (((sign)?'':'-') num '.' cents);
//對整數部分進行千分位格式化.
for (var i = 0; i num = num.substring(0,num.length-(4*i 3)) ','
num.substring( num.length-(4*i 3));
return (((sign)?'':'-') num '.' cents);
}