Simple Guide to Using Math.floor and Math.random in JavaScript

A very basic guide on how to use Math.floor and Math.random in JavaScript, which are commonly used for random number generation and rounding down numbers. This guide assumes you have some basic understanding of JavaScript.

Using Math.floor

  1. What is Math.floor? Math.floor is a JavaScript function that rounds down a number to the nearest whole number (integer). It removes the decimal part of a number, making it smaller or equal to the original number.
  2. Syntax:
   Math.floor(number);
  1. Example:
   var number = 7.9;
   var roundedDown = Math.floor(number);
   console.log(roundedDown); // Output: 7

Using Math.random

  1. What is Math.random? Math.random is a JavaScript function that generates a pseudo-random floating-point number between 0 (inclusive) and 1 (exclusive). In other words, it produces a random decimal number between 0 and 0.999999…
  2. Syntax:
   Math.random();
  1. Example:
   var randomNumber = Math.random();
   console.log(randomNumber); // Output: A random decimal between 0 and 1

Generating Random Integers

If you want to generate random integers within a specific range, you can combine Math.random with Math.floor and some basic math. Here’s an example that generates a random integer between a minimum (inclusive) and a maximum (exclusive) value:

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}

var min = 1; // Minimum value (inclusive)
var max = 10; // Maximum value (exclusive)
var randomInt = getRandomInt(min, max);
console.log(randomInt); // Output: A random integer between 1 and 9

In this example, we multiply the result of Math.random() by the range (max – min) and then add the minimum value min to ensure the generated integer falls within the desired range.

That’s a basic guide on how to use Math.floor and Math.random in JavaScript to work with random numbers and rounding down. These functions are handy for various tasks, including game development, simulations, and data analysis.

Hello, I’m Anuj. I make and teach software.

My website is free of advertisements, affiliate links, tracking or analytics, sponsored posts, and paywalls.
Follow me on LinkedIn, X (twitter) to get timely updates when I post new articles.
My students are the reason this website exists. ❤️

Feedback Display