Hi Friends 👋,
Welcome to Infinitbility ❤️!
Today, we are going to learn How to get a random number in typescript?, here we will use Math.ceil()
, Math.floor()
, and Math.random()
methods to generate random as per our requirement.
Before going to code, let first understand what is those methods.
Math.ceil()
The
Math.ceil()
function always rounds a number up to the next largest integer.Math.floor()
The
Math.floor()
function returns the largest integer less than or equal to a given number.Math.random()
The
Math.round()
function returns the value of a number rounded to the nearest integer.
Here, we will create a custom genrateRandomNumber()
method to generate numbers and it will expect min
and max
from ourselves.
1/**2* Genrate random int3* @param min4* @param max5* @returns random int - min & max inclusive6*/7const genrateRandomNumber = (min: number, max: number) => {8 min: number = Math.ceil(min);9 max: number = Math.floor(max);10 return Math.floor(Math.random() * (max - min + 1)) + min;11}1213genrateRandomNumber();1415genrateRandomNumber(1000, 9000)
When you run the above code,
In the first console, you will get NaN
because it’s expected.
In the second console, you will get some 4-digit random numbers because I have mentioned 1000
to 9000
for generate number.

All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.