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 < 0)
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.50000000001);//把指定的小數位先轉換成整數.多餘的小數位四捨五入.
cents = num%Math.pow(10,cent); //求出小數位元值.
num = Math.floor(num/Math.pow(10,cent)).toString();//求出整數位元值.
cents = cents.toString();//把小數位轉換成字串,以便求小數位長度.
while(cents.length<cent){//補足小數位到指定的位元.
cents = "0" + cents;
}
if(isThousand == 0) //不需要千分位符.
return (((sign)?'':'-') + num + '.' + cents);
//對整數部分進行千分位格式化.
for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
num = num.substring(0,num.length-(4*i+3))+','+
num.substring(num.length-(4*i+3));
return (((sign)?'':'-') + num + '.' + cents);
}