Generate a random integer in p5.js

Nil folquer covarrubias picture Nil folquer covarrubias · Dec 30, 2017 · Viewed 8k times · Source

How can I get a random integer using the random() function in p5.js?

For example this code:

var num = random(0, 1);
console.log(num);

outputs decimal numbers to the console.

How can I get a random integer?

Answer

Relajadito picture Relajadito · Dec 30, 2017

if you want integer numbers from 0 to 10, both inclusive:

var num = int(random(0, 11));
console.log(num);

explanation:

random(0,11) returns numbers from 0 to 10.999999999... but never 11

int() convert those decimal numbers to integer

int( random(0,11) ) returns numbers between 0 and 10, both inclusives.