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

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

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.

Deploying code to production can be filled with uncertainty. Reduce the risks, and deploy earlier and more often. Download this free guide to learn more. Brought to you in partnership with Rollbar.

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 }}