【问题标题】:Math.Random with decimal places and Code Errors in JavascriptMath.Random 带有小数位和 Javascript 中的代码错误
【发布时间】:2023-03-28 12:13:01
【问题描述】:

我怎样才能使用math.random() 获得一个小数点后 2 位的随机数,并可以随意将其更改为 3、4、5 或任何数字?

我在var 上尝试过math.round,但我怎么能这样做,每次我调用某个函数时,小数点的数量都会改变?

【问题讨论】:

  • 如果你想要精确的2个小数位,得到一个6000到6500之间的随机整数,然后除以100。如果你不关心小数位数,更直接的方法是可能的(确实,很容易)。
  • 您读过Math.random() 的工作原理吗? developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • @JohnColeman 刚刚编辑了问题 xD

标签: javascript random


【解决方案1】:

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

你按照约翰科尔曼所说的去做:你生成一个介于 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;
}

【讨论】:

    【解决方案2】:

    试试下面的功能

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 欢迎来到 StackOverflow! (max - 1) 应该是 (max - min)。 (问题下方应该有一个“编辑”链接让您修复它。)
      猜你喜欢
      • 1970-01-01
      • 2018-08-06
      • 1970-01-01
      • 2011-09-20
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-07
      相关资源
      最近更新 更多