向上取整 向下取整 四舍五入 产生特定位数的随机数(4,6....)

对JavaScript中数字的操作

 

parseInt(5.1234);// 1.只保留整数部分(丢弃小数部分)结果为5

 

 

Math.floor(5.1234);//  2.向下取整(<= 该数值的最大整数)和parseInt()执行的结果一样    结果为5    

特殊情况 在当有16位小数 最后一位为大于等于6时取的是该值的整数部分+1

例:   console.log(Math.floor(5.9));// 5

          console.log(Math.floor(5.9999999999999996));// 6

 

 

Math.ceil(8.8888);// 3.向上取整(无论小数点后面是多大都取1,整数部分加1为最后的结果 结果  9

 

Math.round(8.1234);// 4.四舍五入(小数部分大于0.5即入,小于就舍去结果8

Math.round(8.6789);// 5. 结果为 9  

Math.abs(-8);// 6. 取绝对值 结果为8

 

Math.max(7,8);// 7.返回两者中的较大值 结果为8

Math.min(7,8);// 8.返回两者中的较小值  结果为7

 

 

Math.random();// 产生随机数(0-1

console.log(Math.random() * 100);//产生0-100的整数

 

xy之间的随机整数,公式为:

 

1、大减小加1

 

2、乘以随机数

 

3、加上最小数

 

4、向下取整

 

公式:Math.floor(Math.random() * (max - min + 1) + min)

 

 


 

 

function getRandom(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);//公式
}
for (var i = 0; i < 10; i++) { console.log(getRandom(2, 8));// 测试,随机打出2到8之间的随机数 }

 

posted @ 2020-06-24 18:37  小不点灬  阅读(453)  评论(0编辑  收藏  举报