Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Creating Random Numbers in JavaScript

DZone's Guide to

Creating Random Numbers in JavaScript

Brij Mishra talks about random number generation in JavaScript... including how to reach the number 10,000.

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

Have you ever needed to create a random number in JavaScript?

No.

In C#, creating a random number is simple and provides multiple options. Random class is used for the same, it’s Next method is used to create a random number. It also takes min and max value as parameters to create a random number in a range.

In JavaScript, it is more simple. Let’s see...

Math.random is used to create a random number. But, it returns a decimal number between 0 (including) to 1(excluding). For example:

function displayRandom()
{
    alert(Math.random());
}

It will create a different number each time. So, if you want to create a random number say up to 10000 then you can get it by simply writing:

var randomnumber = Math.random() * 10000;

Pretty simple, right?

But, it will always create a number less than 10000 (up to 9999.999..) and if you take the integer part, then the max value you will get is 9999. But, what if want inclusive of 10000?

Then, you can leverage the other method Math.ceil which generates the ceiling number as

Math.ceil(6.0001)

Math.ceil(6.203)

Math.ceil(6.0001)

Math.ceil(6.9001)

For all, you will get 7. So if you write the original method as:


function displayRandom()
{
    alert(Math.ceil(Math.random()));
}

You will get the number between 0 to 10000 both inclusive. You can also use Math.floor or Math.abs to have your own logic for getting a random number in a range.

This is a short post, but I found it a bit interesting and useful to share.

Take a look at the Indigo.Design sample applications to learn more about how apps are created with design to code software.

Topics:
javascript ,random ,c# ,web design and web development

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}