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

  • 相关阅读:
    "Illegal group reference"异常的分析
    一个基于WEB的js时间控件的实现
    ASP.NET网站的网络安全性
    关于"parseInt"
    【C#算法】冒泡排序 选择排序 插入排序 希尔排序转
    【c#】web.config续
    【C#】GridView用法
    [C#]接口引
    【SQL】DBCC
    【C#】泛型
  • 原文地址:https://www.cnblogs.com/mengfangui/p/6607442.html
Copyright © 2020-2023  润新知