JavaScript random generate 0 or 1 integer

Javascript

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser7691120View Question on Stackoverflow
Solution 1 - JavascriptAlexander ElginView Answer on Stackoverflow
Solution 2 - JavascriptbrkView Answer on Stackoverflow