Math()方法

发布于 2020-03-30  467 次阅读


1.随机数:

Math.random()  0 - 1 的随机小数 可以是 0  永远不会是 1
为了更加方便的传递想要范围,可以写成函数:
        //生成 lower - upper 范围内的随机整数,包括 lower , upper 
        function selectFrom(lower, upper) {
            return parseInt( Math.random()*(upper+1-lower) + lower ); 
        }
        document.write(selectFrom(5,10));  //直接传递范围即可

2.小数取整:

四舍五入  Math.round()

        console.log(Math.round(25.9));  //26
        console.log(Math.round(25.5));  //26
        console.log(Math.round(25.48));  //25
        console.log(Math.round(25.1));  //25

进一取整 / 向上取整  Math.ceil()

小数部分一定要有一个非零的数值,才会进一
        alert(Math.ceil(25.9)); //26
        alert(Math.ceil(25.5)); //26
        alert(Math.ceil(25.1)); //26

舍去取整 / 向下取整  Math.floor()

如果只是针对小数,执行效果与 parseInt() 效果相同
        alert(Math.floor(25.9));  //25
        alert(Math.floor(25.5));  //25
        alert(Math.floor(25.1));  //25

保留指定位数的小数 变量.toFixed(保留小数位数)

不会直接改变 变量 中存储的数据,需要使用新的变量来存储 执行结果
执行结果是 字符串类型 需要通过 -0 *1 /1  操作 再转化为数值
保留小数的方法是 四舍五入 保留
        //    保留指定位数的小数  toFixed()
        var int = 123.456789;
        var res = int.toFixed(2)-0;
        console.log( res );
保留指定位数的小数 直接保留,不四舍五入
如果需要保留2位小数
先 乘以 100 , 向下取整/Math.floor()
结果 再 除以 100
        //    不四舍五入,直接保留指定位数的小数
        var int = 123.456789;
        var res = Math.floor(int*100) / 100 ;
        console.log( res );

3.最大值,最小值

Math.max()

        console.log( Math.max(1,2,3,4,5,6) );  //最大值

Math.min()

        console.log( Math.min(1,2,3,4,5,6) );  //最小值

4. 幂运算 / 乘方运算  Math.pow()

执行效果 与 ** 相同
        console.log( Math.pow(2,3) );  //8

5. 绝对值  Math.abs()

        console.log( Math.abs(3) );  //3
        console.log( Math.abs(-3) );  //3

6.平方根  Math.sqrt()

平方根应该是 +/- 两个数值
JavaScript中只获取正数的结果
        console.log( Math.sqrt(4) );  //2

7.圆周率  Math.PI

这是Math的一个属性,没有()的
PI 两个字母都必须要大写
        console.log( Math.PI );  //3.14....

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。