How to generate random number in Javascript?
By Tan Lee Published on Dec 11, 2024 393
In JavaScript, you can generate random numbers using the Math.random() function. This function returns a random floating-point number between 0 and 1.
For example: Random floating-point number between 0 and 1
let randomNumber = Math.random();
To generate a random integer between a minimum (min
) and maximum (max
) value, you can scale and round the result.
For example: Random integer between a specified range
function getRandomInt(min, max) { min = Math.ceil(min); // round up the minimum value max = Math.floor(max); // round down the maximum value return Math.floor(Math.random() * (max - min + 1)) + min; } let randomInt = getRandomInt(1, 10); // Random integer between 1 and 10
If you want a random decimal number within a given range, you can scale the result from Math.random()
accordingly.
For example: Random floating-point number between a specified range
function getRandomFloat(min, max) { return Math.random() * (max - min) + min; } let randomFloat = getRandomFloat(1.5, 5.5); // Random decimal between 1.5 and 5.5
If you need a random boolean value, you can use Math.random()
and check if it is less than 0.5.
For example: Random Boolean (true or false)
let randomBoolean = Math.random() < 0.5;
- How to use sweetalert2
- How to Pass string parameter in an onclick function
- How to format number with commas and decimal in Javascript
- What does 'use strict;' means in Javascript
- How to detect if caps lock is pressed in Javascript
- How to create a Custom Event in Javascript
- How to Check if an Object Has a Property Properly in JavaScript
- How to convert an Uint8Array to string in Javascript
Categories
Popular Posts
Material Lite Admin Template
Nov 14, 2024
HTML Bootstrap 4 Login, Register & Reset Template
Nov 11, 2024
Responsive Animated Login Form
Nov 11, 2024
Portal HTML Bootstrap
Nov 13, 2024