js 實現四捨五入&fixed方法異常處理

JS四捨五入的函數:toFixed(n),n爲要保留的小數位數,n取0~20。javascript

問題:當n超過20的時候,JS會出錯。java

舉例一:git

var d = 10.005;
var f = d.toFixed(2);
alert(f);

輸出結果:10.01函數

舉例二:this

var h = 0.007;
h.toFixed(2);
alert(h);

輸出結果:0.00prototype

解決方案:code

(一)對JS中的Number類型的toFixed方法重寫。ip

Number.prototype.toFixed = function(s) {  
   var changenum = (parseInt(this * Math.pow(10, s) + 0.5) / Math.pow(10, s)).toString();  
   index = changenum.indexOf(".");  
   if (index < 0 && s > 0) {  
      changenum = changenum + ".";  
      for (i = 0; i < s; i++) {  
          changenum = changenum + "0";  
      }  
    } else {  
      index = changenum.length - index;  
      for (i = 0; i < (s - index) + 1; i++) {  
          changenum = changenum + "0";  
      }  
    }  
    return changenum;  
}

(二)利用Math.round函數:取四捨五入的整數部分it

若number的小數部分大於等於0.5,返回值是大於number的最小整數;若number的小數部分小於0.5,返回值是小於等於number的最大整數;io

//Number保留fractionDigits位小數
function Round4(number,fractionDigits){
   return Math.round(number*Math.pow(10,fractionDigits))/Math.pow(10,fractionDigits);
}
//函數調用
var money = 0.00542;
alert(round4(money,4));

輸出結果:0.0054

相關文章
相關標籤/搜索