jacascript Math (算数)对象

前言:这是笔者学习之后自己的理解与整理。如果有错误或者疑问的地方,请大家指正,我会持续更新!

  实际应用中用的比较多的有:round(); random(); floor(); ceil();

  其次还有 pow(); sqrt(); abs(); sin(); cos(); tan();

Math.round(num)

  把数四舍五入为最接近的整数。

        <script type="text/javascript">
            //Math.round(num)把数四舍五入为最接近的整数。
            console.log(Math.round(3.49999));//3
            console.log(Math.round(3.50123));//4
            
            console.log(Math.round(3.14159265358));//3
            //小数位四舍五入用Obj.toFixed(num);方法
            var aaa = 3.14159265358
            console.log(aaa.toFixed(3));//3.142
        </script>

Math.floor(num)

  把数向下取舍为最接近的整数。

        <script type="text/javascript">
            //Math.floor(num)把数向下取舍为最接近的整数。
            console.log(Math.floor(3.49999));//3
            console.log(Math.floor(3.99999));//3
        </script>

Math.ceil(num)

  把数向上取舍为最接近的整数。

        <script type="text/javascript">
            //Math.ceil(num)把数向上取舍为最接近的整数。
            console.log(Math.ceil(3.00001));//4
        </script>

Math.random()

  [0-1) 之间的(包含0,不包含1) 一个伪随机数。

  每次运算都可能不一样;

        <script type="text/javascript">
            //Math.random()  [0-1)之间的(包含0,不包含1) 一个伪随机数。
            //0---X之间(包含0和X)取整;Math.round(Math.random()*X);
            //0---X之间(包含0,不包含X)取整;Math.floor(Math.random()*X);
            //0---X之间(不包含0,包含X)取整;Math.ceil(Math.random()*X);
            
            //X---Y之间(包含X和Y)取整;Math.round(Math.random()*(Y-X))+X;
            //X---Y之间(包含X,不包含Y)取整;Math.floor(Math.random()*(Y-X))+X;
            //X---Y之间(不包含X和不包含Y)取整;Math.ceil(Math.random()*(Y-X))+X;
        </script>
原文地址:https://www.cnblogs.com/sspeng/p/6577389.html