1

I have to generate a random number in a range between 0.1 and 1.5. What could be the exact command?

const random = +(Math.random() * ((1.5- 0.1) + 0.1)).toFixed(1);
console.log(random)
adiga
  • 34,372
  • 9
  • 61
  • 83
  • @str annoyingly, that is for whole numbers, whereas OP wants floats. There isn't a big change needed but it's just annoying we don't have something generic enough cover both easily. – VLAZ Jun 03 '19 at 10:53
  • please describe what's wrong with the solution you've proposed – YakovL Jun 03 '19 at 12:11

3 Answers3

1

If you want the random numbers with 0.1 steps, the easiest would be to generate a random number between 1 and 15, then divide the result by 10.

(Math.floor(Math.random() * 15) + 1) / 10;
0

Mah.random() * (max - min) + min is always your best bet. If you want to round it to n decimals later, just wrap it like so: Math.round(random * 10 ** n) / (10 ** n)

In the case of one decimal, that is Math.round(10 * (Math.random() * (max - min) + min)) / 10

Ruben Helsloot
  • 12,582
  • 6
  • 26
  • 49
0

You coudl take the factor 15 for the random value and take the integer value of the divided value by 10.

function getRandom() {
    return (Math.floor(Math.random() * 15) + 1) / 10;
}

var i = 1e6,
    r,
    d = {};

while (i--) {
    r = getRandom();
    d[r] = (d[r] || 0) + 1;
}

console.log(d);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392