JS Math.round()方法原理


 請先測試代碼:

 1 <!doctype html>
 2 <html lang="en">
 3 
 4     <head>
 5         <meta charset="UTF-8" />
 6         <title>Math.round方法</title>
 7         <style type="text/css">
 8             * {
 9                 padding: 0;
10                 margin: 0;
11             }
12         </style>
13     </head>
14 
15     <body>
16         <script type="text/javascript">
17             Math.round(1.0);//1
18             Math.round(1.4);//1
19             Math.round(1.5);//2
20             Math.round(1.6);//2
21             Math.round(-1.0);//-1
22             Math.round(-1.4);//-1
23  Math.round(-1.5);//-1
24             Math.round(-1.6);//-2
25         </script>
26     </body>
27 
28 </html>

尤其注意: Math.round(-1.5);//-1

 

原理是:

實際上,Math.round()方法准確說是“四舍六入”,對0.5要進行判斷對待。 
Math.round()的原理是對傳入的參數+0.5之后,再向下取整得到的數就是返回的結果。這里的向下取整是說取比它小的第一個整數或者和它相等的整數。

因此Math.round(-1.5)的結果是-1.5 + 0.5 再向下取整,即-1.0取整,結果是-1.。
Math.round(-1.4)的結果是 -1.4 + 0.5 即-0.9 向下取整,結果是-1。 
同理,Math.round(1.5)即為 1.5 + 0.5 再向下取整,結果是2。

 

總結:數值+0.5后,向下取整。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM