Navigate back to the homepage

How to get random number in typescript?

Infinitbility
TypeScript
May 8th, 2022 · 1 min read

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.

`.css-1chxjt6{position:absolute;right:22px;top:24px;padding:8px 12px 7px;border-radius:5px;color:#6f7177;-webkit-transition:background 0.3s ease;transition:background 0.3s ease;}.css-1chxjt6:hover{background:rgba(255,255,255,0.07);}.css-1chxjt6[data-a11y="true"]:focus::after{content:"";position:absolute;left:-2%;top:-2%;width:104%;height:104%;border:2px solid var(--theme-ui-colors-accent,#6166DC);border-radius:5px;background:rgba(255,255,255,0.01);}@media (max-width:45.9375em){.css-1chxjt6{display:none;}}1/**2* Genrate random int3* @param min 4* @param max 5* @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 👍.

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.

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.

Request New Tutorial or Article on mail [email protected]

Guide book

Guidebook: The Javascript Monorepo Photoshop Guide

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