js中的随机数和小数取整
小数取整
(1)parseInt(5/2) 丢弃小数部分 保留整数
console.log(parseInt(5/2)); //====> 2
(2)Math.ceil(5/2) 向上取整,有小数就向上加一
console.log(parseInt(Math.ceil(5/2))); //====> 3
(3)Math.floor(5/2) 向下取整
console.log(parseInt(Math.floor(5/2))); //====> 2
(4)Math.round(5/2) 四舍五入
console.log(parseInt(Math.round(5/2))); //====> 3
随机数的使用方法 ==》Math.random();
用法1:生成一个min-max之间的随机整数
parseInt(Math.random()*(max-min+1)+min );
用法2:生成指定位数的随机数 使用字符串拼接0-9之间的随机数,得到指定位数的随机数
function randomNum(n){
var t='';
for (let i = 0; i < n; i++) {
t+Math.floor(Math.random()*10);
}
return t;
}
document.write(randomNum(5));