打赏

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后,向下取整。

posted @ 2017-03-23 21:29  孟繁贵  阅读(11786)  评论(0编辑  收藏  举报
TOP