當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JS Math.round()方法原理
生活随笔
收集整理的這篇文章主要介紹了
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后,向下取整。
轉載于:https://www.cnblogs.com/mengfangui/p/6607442.html
總結
以上是生活随笔為你收集整理的JS Math.round()方法原理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 华为鸿蒙OS 3 Beta版最新升级名单
- 下一篇: javascript之变量