js輸出資料精確到小數點後n位代碼_javascript技巧

來源:互聯網
上載者:User

編寫兩種方法,可以輸出資料 num 精確到小數點後第 n 位,具體內容如下

1. 藉助於 Math.pow(10,n);
2. 藉助於 ..toFixed(n) (JS 1.5(IE5.5+,NS6+以上版本支援)。
測試 pi=3.14159265 的輸出結果:
精確到小數點後 n 位, 藉助於 Math.pow(10,n):
3.1
3.14
3.142
3.1416
精確到小數點後 n 位, 藉助於 ..toFixed(n):
3.1
3.14
3.142
3.1416

<html><head>  <title>四捨五入</title>  <meta charset="utf-8"></head><body><script>function round_1(num,n){//返回數字 num, 精確到小數點後 n 位  var number= Math.round(num*Math.pow(10,n));  return number/Math.pow(10,n);}function round_2(num,n){//返回數字 num, 精確到小數點後 n 位  return num.toFixed(n); //JS 1.5(IE5.5+,NS6+以上版本支援)}var pi= 3.14159265;document.write("精確到小數點後 n 位, 藉助於 Math.pow(10,n):<br>");for (var i=1; i<5; i++)document.write(round_1(pi,i) + "<br>"); document.write("精確到小數點後 n 位, 藉助於 ..toFixed(n):<br>");for (var i=1; i<5; i++)document.write(round_2(pi,i) + "<br>");</script> </body></html>

以上就是本文的全部內容,希望對大家學習javas程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.