js随机数和小数取整

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));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值