83

I am trying to generate random 0 or 1 as I am writing a script to populdate my database. If it is 1, I will save it as male and 0 the other way around.

Inside my JavaScript:

Math.floor((Math.random() * 1) + 1);

I used this to generate either 1 or 0. However, with the code above, it always return me with 1. Any ideas?

2 Answers2

223

You can use Math.round(Math.random()). If Math.random() generates a number less than 0.5 the result will be 0 otherwise it should be 1.

Alexander Elgin
  • 6,796
  • 4
  • 40
  • 50
2

There is a +1 with Math.random, so it will always going to add 1 to the randomly generated number. You can just randomly generate a number, since Math.random will generate any floating number between 0 & 1, then use if.. else to assign 0 or 1

var y = Math.random();
if (y < 0.5)
  y = 0
else
  y= 1
console.log(y)
Community
  • 1
  • 1
brk
  • 48,835
  • 10
  • 56
  • 78