Hello everyone hope everyone is doing well. My name is Surya L, The purpose of this blog is to teach you all about Math.random() & Math.floor() and build your own love calculator❤.
The Math.random() function in JavaScript generates a random number between 0 (inclusive) and 1 (exclusive). As a result, Math.random() can return 0 but not 1.
function randomFraction() {
return Math.random();
}
randomFraction();
The output of above Code 👇 0.56
In the Above code Math.random( ) generates random value from 0 to 0.9999 but it never returns 1.
Math.floor( ) is a JavaScript function used to round the number down to its nearest whole number.
console.log(Math.floor(56.9));
//The math.floor rounds the value 56.9 to 57
It's great that we can generate random decimal numbers, but it's even more useful if we use it to generate random whole numbers.
- Use Math.random() to generate a random decimal.
- Multiply that random decimal by 100.
- Use another function, Math.floor() to round the number down to its nearest whole number.
console.log(Math.floor(Math.random() * 100));
The output of above Code 👇
6
console.log(Math.floor(Math.random() * 100)+1);
The output of above Code 👇
100
Create a Function called as loveCalculator which takes input lover1 and lover2 Use Math.random() to generate a random decimal. Multiply that random decimal by 100. Use Math.floor() to round the number down to its nearest whole number. Add 1 to Math.floor(Math.random() * 100); to get 100% Console (Math.floor(Math.random() * 100)+1); Call the function loveCalculator by giving values for lover1 and lover2
function loveCalculator(lover1,lover2)
{
console.log("The lovers "+lover1+" and "+lover2+" has "+(Math.floor(Math.random() * 100)+1)+" % ❤love");
}
loveCalculator("Ram","Sam");
The output of above Code 👇
**The lovers Ram and Sam has 24 % love **
- The Math.random() function in JavaScript generates a random number between 0 (inclusive) and 1 (exclusive). As a result, Math.random() can return 0 but not 1.
- Math.floor( ) is a JavaScript function used to round the number down to its nearest whole number.
**Credits: I learned this topics in FreeCodeCamp which I explained in minified version
Thanks for reading the blog. Do let me know what you think about it.**
You can connect with Showwcase Twitter Blog GitHub Contact Me