Math.Random with 小数位和 Javascript 中的代码错误



如何使用math.random()获得小数点后 2 位的随机数,并可以自由地将其更改为 3、4、5 或任何数字?

我已经尝试在varmath.round,但是我该如何以某种方式做到这一点,每次调用某个函数时,小数大小写的数量都会发生变化?

我找不到这个的欺骗目标,所以:

你按照约翰·科尔曼(John Coleman(所说的去做:你生成一个介于6000和6500之间的随机数:

var num = Math.floor(Math.random() * 500) + 6000;

。并除以 100:

var num = (Math.floor(Math.random() * 500) + 6000) / 100;
// New bit ---------------------------------------^^^^^^

这给你一个从60(含(到65(不包括(的数字,小数部分理论上大约是两位数,但由于IEEE-754双精度二进制浮点数(JavaScript使用的数字类型(的工作方式,如果你输出它,你可能会得到更多或更少的数字在小数点。

两位数输出它,请使用toFixed(2)

console.log(num.toFixed(2));

例:

var counter = 0;
tick();
function tick() {
    var num = (Math.floor(Math.random() * 500) + 6000) / 100;
    console.log(num.toFixed(2));
    if (counter++ < 100) {
        setTimeout(tick, 250);
    }
}
.as-console-wrapper {
  max-height: 100% !important;
}

尝试以下函数

    function getRandomArbitrary(min, max) {
      return ((Math.random() * (max - min)) + min).toFixed(2);
    }
    
    console.log(getRandomArbitrary(60, 65));

此函数将返回两个数字之间的随机数,带有随机小数。

var randomDec = function(min, max, places){
    return parseFloat(
        (Math.floor(Math.random() * (max -1))  + min ) 
        + ( '.' + ( Math.floor(Math.random() * Math.pow(10, places)) + 1))
    );
}

最新更新