Rand() | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Rand()

Is there an equivalent of rand () in javascript?

11th Jul 2018, 11:48 AM
Omar Semma
Omar Semma - avatar
4 Answers
+ 5
Hello, Omar Alex ! The function Math.random returns a random fractional number from 0 to 1. Syntax Math.random(); To get a random number in a certain interval (fractional or whole), you should use special methods: Random fractional number between min and max function getRandomArbitary (min, max) { return Math.random() * (max - min) + min; } https://www.sololearn.com/Course/JavaScript/?ref=app
11th Jul 2018, 11:50 AM
Alexander Sokolov
Alexander Sokolov - avatar
+ 4
Math.random() is used.However it returns float values between 0 and 1. To get integer values use: Math.ceil(Math.random()) or Math.floor(Math.random()). Eg: To generate a no between 0 and 100 You can use. Math.ceil(Math.random()*99) or Math.floor(Math.random()*100). Hope this helps you,Omar Alex .
12th Jul 2018, 5:37 AM
Aanisha Bhattacharyya
Aanisha Bhattacharyya - avatar
+ 4
Use this function: function boundValue(min,max) { return Math.random()*(max-min)+min; } The value returned is bound by min & max values. min <= x <= max e.g. min = 2 , max = 4; for(var i=0; i<20; i++) { console.log(boundValue(min,max)); } will return 20 values between 2 & 4
12th Jul 2018, 10:12 AM
Haris
Haris - avatar
0
If you want an integer, use Math.floor(/*numbers here*/) to remove the decimals.
11th Jul 2018, 12:21 PM
James
James - avatar