Over a million developers have joined DZone.

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

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.

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

Published at DZone with permission of Brij Mishra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

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

{{ parent.tldr }}

{{ parent.urlSource.name }}