Math对象

168 阅读1分钟

Math对象:不是一个构造函数,所以不需要new来调用,而是直接使用

1.三种取整的方法:

(1)Math.floor():向下取整,往最小了取值

console.log(Math.floor(1.9));输出结果为1;

console.log(Math.floor(1.1));输出结果为1;

(2)Math.ceil();向上取整,往最大了取值

console.log(Math.ceil(1.9));输出结果为2;

console.log(Math.ceil(1.2));输出结果为2;

(3)Math.round():四舍五入,.5是特殊情况,无论正负,.5都往大了取

console.log(Math.round(1.9));输出结果为2;

console.log(Math.round(1.2));输出结果为1;

console.log(Math.round(-1.5));输出结果为-1;

(4)随机数方法Math.random();返回的是一个随机小数,范围为0-1,包括0但是不包括1

也可以返回整数,但是需要用到取整

随机数公式:

得到两数之间的随机整数,不含最大值,含最小值:Math.floor(Math.random() * (max - min))+min;

得到两数之间的随机整数,含最大值,含最小值:Math.floor(Math.random() * (max - min+1))+min;