Skip to content
Fix Code Error

Generate random number between two numbers in JavaScript

March 13, 2021 by Code Error
Posted By: Anonymous

Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?

Solution

Important

The following code works only if the minimum value is 1. It does not work for minimum values other than 1.

If you wanted to get a random integer between 1 (and only 1) and 6, you would calculate:

Math.floor(Math.random() * 6) + 1  

Where:

  • 1 is the start number
  • 6 is the number of possible results (1 + start (6) – end (1))
Answered By: Anonymous

Related Articles

  • Dynamically update values of a chartjs chart
  • How do I include certain conditions in SQL Count
  • Form field border-radius is not working only on the last…
  • Generate single complex JSON object from PostgreSQL query
  • How to print binary tree diagram?
  • Checking if a variable is an integer in PHP
  • Unexpected end of JSON input while parsing
  • Generating random whole numbers in JavaScript in a specific…
  • 3D Rotation of a camera using its own, new axes
  • How to generate a random string of a fixed length in Go?

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I do an UPDATE statement with JOIN in SQL Server?

Next Post:

Best way to convert string to bytes in Python 3?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

  • Get code errors & solutions at akashmittal.com
© 2022 Fix Code Error