一、Math.round()
作用:四舍五入返回整數。(返回參數+0.5后,向下取整)
Math.round(5.57) //返回6
Math.round(2.4) //返回2
Math.round(-1.5) //返回-1
Math.round(-5.8) //返回-6
二、Math.ceil()
作用:返回大於等於參數的最小整數。
Math.ceil(5.57) //返回6
Math.ceil(2.4) //返回3
Math.ceil(-1.5) //返回-1
Math.ceil(-5.8) //返回-5
三、Math.floor()
作用:返回小於等於參數的最大整數。
Math.floor(5.57) //返回5
Math.floor(2.4) //返回2
Math.floor(-1.5) //返回-2
Math.floor(-5.8) //返回-6
四、parseInt()
作用:解析一個字符串,並返回一個整數,這里可以簡單理解成返回舍去參數的小數部分后的整數。
parseInt(5.57) //返回5
parseInt(2.4) //返回2
parseInt(-1.5) //返回-1
parseInt(-5.8) //返回-5
正數轉換和Math.floor()一樣,負數不一樣
五、 Math.random()
該方法可返回介於 0 ~ 1 之間的一個隨機數
如果你希望生成任意值到任意值的隨機數,公式就是這樣的:
// max - 期望的最大值, min - 期望的最小值
parseInt(Math.random()*(max-min+1)+min,10);
Math.floor(Math.random()*(max-min+1)+min);