JavaScript Math对象

157 阅读1分钟

1. ceil()

对数进行上舍入。
Math.ceil(25.1) = 26
Math.ceil(25.9) = 26
Math.ceil(-25.9) = -25

2. floor()

对数进行下舍入。
Math.floor(25.1) = 25
Math.floor(25.9) = 25
Math.floor(-25.4) = -26

3. round()

把数四舍五入为最接近的数。
Math.round(25.6) = 26
Math.round(25.4) = 25
Math.round(-25.4) = -25
Math.round(-25.6) = -26
Math.round(25.5) = 26
⭐特殊点:满足两个条件 ① 负数, ② 小数位是5
Math.round(-25.5) = -25

4. random()

返回 0.0~1.0 之间的随机数。包括 0 ,但是不包括 1 。

⭐公式: Math.floor( Math.random()*(max-min) ) + min
随机出现 1-10 之间的数,包括 1 ,不包括 10
document.write( Math.floor(Math.random()*(10-1)) + 1 );

⭐公式:Math.floor( Math.random()*(max-min+1) ) + min
随机出现 2-10 之间的数,包括 2 ,也包括 10
document.write( Math.floor(Math.random()*(10-2+1)) + 2 );