随机数的获取

Math.ceil();  //向上取整。

Math.floor();  //向下取整。

Math.round();  //四舍五入。

Math.random();  //0.0 ~ 1.0 之间的一个伪随机数。【包含0不包含1】 //比如0.8647578968666494

Math.ceil(Math.random()*10);      // 获取从1到10的随机整数 ,取0的概率极小。

Math.round(Math.random());   //可均衡获取0到1的随机整数。

Math.floor(Math.random()*10);  //可均衡获取0到9的随机整数。

Math.round(Math.random()*10);  //基本均衡获取0到10的随机整数,其中获取最小值0和最大值10的几率少一半。
 因为结果在 0~0.4 为 0,0.5 到 1.4 为 1,8.5 到 9.4 为 9,9.5 到 9.9 为 10。所以头尾的分布区间只有其他数字的一半。

获取一个随机数:
function getRandom() {
    return Math.round(Math.random()*10)
}
console.log(getRandom())

获取两个数之间的随机数:
function getRandom(min,max) {
    return Math.random()*(max-min)+min;
}
console.log(getRandom(1,5))

获取两个数之间的随机整数(含最小值不含最大值):
function getRandomInt(min,max) {
    min=Math.ceil(min) //向上取整
    max=Math.floor(max)//向下取整
    return Math.floor(Math.random()*(max-min)) +min//含最大值,不含最小值
}
console.log(getRandomInt(1,5))
获取两个数之间的随机整数(含最小值也含最大值):
function getRandomIntInclusive(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值
}
console.log(getRandomIntInclusive(1,5));
请注意, 由于 JavaScript 中的数字是 IEEE 754 浮点数字,具有最近舍入( round-to-nearest-even)的行为, 因此以下函数的范围 (不包括Math.random () 本身) 并不准确。如果选择了非常大的边界 (253 或更高), 在极罕见的情况下会计算通常-排除(usually-excluded)的上界。

IEEE 754标准的默认模式是最近舍入(舍入为最接近的偶数),它与四舍五入不同的是,对.5的舍入上采用取偶数的方式,即round-to-nearest-even,如:

Round to nearest even:Round(0.5) = 0; Round(1.5) = 2; Round(2.5) = 2;Round(3.5) = 4;

"四舍六入五取偶"
“五取偶”的规则:当小数部分恰为0.5时,若个位是奇数则入,若个位是偶数则舍,总之让个位变成偶数。

var a=1.55;
var b=1.65;
var c=a.toFixed(1);
var d=b.toFixed(1);
console.log(c);
console.log(d);



 
 



 

原文地址:https://www.cnblogs.com/hy96/p/11374006.html