JavaScript js 精確、保留小數方法

來源:互聯網
上載者:User

做BS的兄弟都知道js,我們搞Bs就少不了要和js打些交道。不會一定js還真是不行,有些的地方就是離不開js。在form表單中,有時候會要保留小數。精確小數點到多少位。那麼下面的一些方法就可以幫我們做到。</p><p><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><br /><html><br /> <head><br /> <title>floatDecimal.html</title></p><p> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><br /> <meta http-equiv="description" content="this is my page"><br /> <meta http-equiv="content-type" content="text/html; charset=UTF-8"><br /> <script type="text/javascript"><br /> //保留兩位小數<br /> //功能:將浮點數四捨五入,取小數點後2位<br />function toDecimal(x) {<br />var f = parseFloat(x);<br />if (isNaN(f)) {<br />return;<br />}<br />f = Math.round(x*100)/100;<br />return f;<br />}</p><p>//制保留2位小數,如:2,會在2後面補上00.即2.00<br />function toDecimal2(x) {<br />var f = parseFloat(x);<br />if (isNaN(f)) {<br />return false;<br />}<br />var f = Math.round(x*100)/100;<br />var s = f.toString();<br />var rs = s.indexOf('.');<br />if (rs < 0) {<br />rs = s.length;<br />s += '.';<br />}<br />while (s.length <= rs + 2) {<br />s += '0';<br />}<br />return s;<br />}</p><p>function fomatFloat(src,pos){<br /> return Math.round(src*Math.pow(10, pos))/Math.pow(10, pos);<br /> }<br />//四捨五入<br /> alert("保留2位小數:" + toDecimal(3.14159267));<br /> alert("強制保留2位小數:" + toDecimal2(3.14159267));<br /> alert("保留2位小數:" + toDecimal(3.14559267));<br /> alert("強制保留2位小數:" + toDecimal2(3.15159267));<br /> alert("保留2位小數:" + fomatFloat(3.14559267, 2));<br /> alert("保留1位小數:" + fomatFloat(3.15159267, 1));</p><p> //五舍六入<br /> alert("保留2位小數:" + 1000.003.toFixed(2));<br /> alert("保留1位小數:" + 1000.08.toFixed(1));<br /> alert("保留1位小數:" + 1000.04.toFixed(1));<br /> alert("保留1位小數:" + 1000.05.toFixed(1));</p><p> //科學計數<br /> alert(3.1415.toExponential(2));<br /> alert(3.1455.toExponential(2));<br /> alert(3.1445.toExponential(2));<br /> alert(3.1465.toExponential(2));<br /> alert(3.1665.toExponential(1));<br /> //精確到n位,不含n位<br /> alert("精確到小數點第2位" + 3.1415.toPrecision(2));<br /> alert("精確到小數點第3位" + 3.1465.toPrecision(3));<br /> alert("精確到小數點第2位" + 3.1415.toPrecision(2));<br /> alert("精確到小數點第2位" + 3.1455.toPrecision(2));<br /> alert("精確到小數點第5位" + 3.141592679287.toPrecision(5));<br /> </script></p><p> </head></p><p> <body><br /> This is my HTML page. <br><br /> </body><br /></html><br />

 

 

相關文章

聯繫我們

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