JavaScript中的四捨五入函數小結方法

來源:互聯網
上載者:User

之前,我是一個JavaScript小白,對jQuery的理解也僅限於準系統的使用。最近在看《JavaScript DOM編程藝術》,算是在自學一點兒基礎知識。執行個體中有一個函數需要對結果進行四捨五入,保留小數點後一位元字。然後就查閱了W3School的參考文檔,發現Number對象有一個toFixed()方法,完全符合我的要求。

toFixed(num)只有一個參數num,用來規定需要保留的小數位元,111cn.net取值在0~20之間,超出這個範圍則拋出異常。當然,如果調用這個方法的對象不是一個Number時也會拋出異常。

 代碼如下 複製代碼

var num = 10/3;
alert(num.toFixed(2));


執行上面的代碼,可以看到輸出的結果是3.33

num參數可以省略,如果省略的話,預設將用0代替,即四捨五入為整數。

值得注意的是,toFixed方法在不同瀏覽器下表現可能會有差異。比如

 代碼如下 複製代碼

var money=0.00542;//0.006;
alert(Number(money).toFixed(2));
//在IE6~7中為0.00


顯然,這個方法是需要改進的。用Math對象的Round方法寫一個函數即可解決。

 代碼如下 複製代碼
//對數值進行四捨五入的函數
function roundNum(number,fDigits){  
    with(Math){  
        return round(number*pow(10,fDigits))/pow(10,fDigits);  
    }  
}
//用roundNum函數對數值進行四捨五入操作
function showNum() {
    var num = 0.006;
    alert(roundNum(num,2));
}

 
執行上面的代碼後我們可以看到,輸出的結果是0.01,是正確的。round方法是返回與給出的數值運算式最接近的整數。如果 number 的小數部分大於等於 0.5,傳回值是大於 number 的最小整數。否則,round 返回小於等於 number 的最大整數。

Math.round()與Math.pow()

 

 代碼如下 複製代碼

<script type="text/javascript">
//Math.round(x);返回數字最接近的整數,四捨五入取整數,即捨去小數部分
function f(){
alert(Math.round(123.567));
alert(Math.round(123.456));
}
//Math.pow(x,y);返回底數的指定次冪
//返回以x的y次冪,等同於x的y次冪的數值運算式
//如果pow的參數過大而引起浮點溢出,www.111cn.Net返回Infinity
function f1(){
alert(Math.pow(2,10));//2的10次方等於1024
alert(Math.pow(1024,0.1));//1024的0.1次方等於2
alert(Math.pow(99,9999));//溢出則返回Infinity
}
/*Javascript設定要保留的小數位元,四捨五入。
*ForDight(Dight,How):數值格式化函數,Dight要格式化的 數字,How要保留的小數位元。
*這裡的方法是先乘以10的倍數,然後去掉小數,最後再除以10的倍數。
*/
function ForDight(Dight,How){
Dight = Math.round(Dight*Math.pow(10,How))/Math.pow(10,How);
return Dight;
}
function f2(){
alert(ForDight(12345.67890,3));//保留三位小數
alert(ForDight(123.99999,4));//保留四位小數
}
//另外一種四捨五入的方法,原理一樣。
//裡面的兩個參數:num就是要轉換的資料。n為要轉換的位元
//cheng(123.456,2);//保留兩位小數
function cheng(num,n){
var dd=1;
var tempnum;
for(i=0;i<n;i++){
dd*=10;
}
tempnum = num*dd;
tempnum = Math.round(tempnum);
alert(tempnum/dd);
}
</script>

<input type="button" value="round" onclick="f();" />
<input type="button" value="pow" onclick="f1();" />
<input type="button" value="設定要保留的小數位元,四捨五入" onclick="f2();" />
<input type="button" value="cheng" onclick="cheng(123.456,2);" />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.