Navigate back to the homepage

How to get random number in typescript?

Infinitbility
TypeScript
May 8th, 2022 · 1 min read
keep affilitate

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.

  1. Math.ceil()

    The Math.ceil() function always rounds a number up to the next largest integer.

  2. Math.floor()

    The Math.floor() function returns the largest integer less than or equal to a given number.

  3. 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 int
3* @param min
4* @param max
5* @returns random int - min & max inclusive
6*/
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}
12
13genrateRandomNumber();
14
15genrateRandomNumber(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.

TypeScript, get random number example
TypeScript, get random number example

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.

melio affilitate

Looking For React Native Tutorial?

we are trying to create the best Tutorial for react native developers.

When you want a daily updates about React Native Tutorial or infinitbility update subscribe to our newsletter.

Read React Native Tutorial

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo Photoshop Guide

Tutorials

Categories

More articles from Infinitbility

How to get value from object by key in typescript?

TypeScript, get value from object by key example with step by step guide.

May 7th, 2022 · 1 min read

How to get first 5 elements of array in javascript?

Example of get first 5 elements of array in javascript with step by step guide.

May 6th, 2022 · 1 min read
© 2020–2022 Infinitbility
About
Link to $https://medium.com/infinitbilityLink to $https://www.facebook.com/InfinitbilityLink to $https://github.com/infinitbilityLink to $https://twitter.com/infinitbilityLink to $https://www.buymeacoffee.com/infinitbilityLink to $mailto:[email protected]