• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / Math Related / Generating random numbers with JavaScript

Generating random numbers with JavaScript

Generating random numbers with JavaScript

The Math.random() method generates a random float (a number with decimals) between 0 and 1. What if you wanted a random integer, or whole number, instead of a float?

In this snippet, look at how to get a random integer between two numbers. For example, let’s say you wanted a number that was at least 5, but no bigger than 42.

var randomNumber = function (min, max) {
	return Math.floor(Math.random() * (max - min + 1) + min);
};

// Logs something like 37
var rand = randomNumber(5, 42);
console.log(rand);

Source

https://gomakethings.com/generating-random-numbers-with-vanilla-js/

Math Related

Related Snippets:

  • Take a number and return it in the specified currency formatting
  • GCD/LCM Calculator
  • Convert a string into an integer (a whole number)
  • The JavaScript function Math.pow()

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers