zoukankan      html  css  js  c++  java
  • 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后,向下取整。

  • 相关阅读:
    来电科技-自助租借充电宝
    一次使用NodeJS实现网页爬虫记
    八爪鱼采集器
    杭州市职称系统
    zz
    有道智选-网易效果推广
    Ubuntu10.04下载并编译Android4.3源代码
    poj 1654 Area 多边形面积
    Android利用Looper在子线程中改变UI
    Notepad 快捷键 大全
  • 原文地址:https://www.cnblogs.com/mengfangui/p/6607442.html
Copyright © 2011-2022 走看看