May 1, 2011

Generating a random number in JavaScript


Today I was working in a DayPilot project it was something like Google or outlook calender. In that project when I was creating or editing event, it was using java script popup. But it was showing old value rather than new or updated value when popup open. This was happening due to JavaScript because it was running from cache. 
How to fill new or updated value in control it was a big concern? So what I had done is just create one random number and append it at the end of URL so every time new http request will be different in browser and it will not run from cache.

So now how to generate a random number?

Lets begin by looking back. As discussed in this post to generate a random number in JavaScript, the code:

var randomnumber=Math.random();

Math.random(x)
                  This is the function which will return next random number between 0.0 to 0.999999 so this will generate decimal number every time. If we require integer number then we can convert it using either round or floor function.

Math.round(x)
                  The round() method rounds a number to the nearest integer.

Math.floor(x)
                   The floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result.

So finally we can use it as like this


randomnumber = Math.floor(Math.random());
or

randomnumber = Math.round(Math.random());

it will return value between 0 to 9



0 comments:

Post a Comment

Author Profile

Total Pageviews

Categories

Followers

 
Top Programming   Sites Technology Top Blogs Technology blogs Technology Blogs

Sponsors