How can I make 2.5% in Javascript?

Viewed 47
function rand() {
    num = Math.floor(Math.random() * 100)
  
    if (num == 0 || num == 1) { //2%
      div.text(num + "you win!")
    }
    count += 1
    counter.text('count : ' + count)
}

How can I make 0.5% with Math.random() here?

2 Answers

Since you are using a floor function and wants more accuracy than 1-100 percent, I would use a range of 1000 numbers instead.

This way if the random function would return 0-4 it would mean that it is with a probability of 5/1000 = 0.5%. The random function would return numbers between 0-999 not including 1000.

function rand() {
    num = Math.floor(Math.random() * 1000)
  
    if (num < 20) { //2%
      div.text(num + "you win!")
    }
    if (num < 5) { //0.5%
      div.text(num + "you win!")
    }
    count += 1
    counter.text('count : ' + count)
}
num = Math.round(Math.random() * 100) / 100
Related