{"id":4468,"date":"2016-03-02T11:34:18","date_gmt":"2016-03-02T11:34:18","guid":{"rendered":"http:\/\/www.hostingnotes.com\/?p=4468"},"modified":"2017-10-09T14:38:29","modified_gmt":"2017-10-09T14:38:29","slug":"generating-random-numbers-in-javascript","status":"publish","type":"post","link":"https:\/\/www.webdevelopersnotes.com\/generating-random-numbers-in-javascript","title":{"rendered":"Generating Random Numbers in JavaScript"},"content":{"rendered":"<p>To generate random numbers with JavaScript we employ the <span class=\"codeword\"><strong>random()<\/strong><\/span> method of the <span class=\"codeword\"><strong>Math<\/strong><\/span> object. It returns a floating-point number between 0.0 and 1.0.<br \/>JavaScript <strong>Math<\/strong> object has several methods and we shall encounter three on this page &#8211; the first one being <span class=\"codeword\">random()<\/span>.<\/p>\n<pre class=\"small-text\">\r\nvar rand_no = Math.random();\r\nalert(rand_no);\r\n<\/pre>\n<p>In the code above, the <span class=\"codeword\">random()<\/span> method returns the number which we store in the variable <span class=\"codeword\">rand_no<\/span> and display through <span class=\"codeword\">alert()<\/span>.<\/p>\n<p><a href=\"javascript:void()\" onclick=\"var rand_no = Math.random();alert(rand_no);\">Click to display a random number<\/a>.<br \/> You&#8217;ll notice that each time you click the link a new random number is generated and displayed.<\/p>\n<div class=\"clr\"><\/div>\n<div class=\"bottom-ads\">\n<h4>Sponsored Links<\/h4>\n<script async src=\"\/\/pagead2.googlesyndication.com\/pagead\/js\/adsbygoogle.js\"><\/script>\n<!-- Inner Page Top - Non Responsive -->\n<ins class=\"adsbygoogle\"\n     style=\"display:inline-block;width:336px;height:280px\"\n     data-ad-client=\"ca-pub-1043128618639037\"\n     data-ad-slot=\"5670477364\"><\/ins>\n<script>\n(adsbygoogle = window.adsbygoogle || []).push({});\n<\/script>\n<\/div>\n<div class=\"clr\"><\/div>\n<p>Now that we have our randomly generated number with JavaScript, let us see how we can use it in some of our applications.<\/p>\n<h2>How to use JavaScript random number<\/h2>\n<p>Suppose you want a random number between 1 and 100. How do you get it from the long decimal number thrown up by the <span class=\"codeword\">random()<\/span> method?<\/p>\n<p>The first step is to multiply the long decimal random number generated by the random() method with 100.<\/p>\n<pre class=\"small-text\">\r\nvar rand_no = Math.random();\r\nrand_no = rand_no * 100;\r\nalert(rand_no);\r\n<\/pre>\n<p><a href=\"javascript:void(0)\" onclick=\"var rand_no = Math.random();rand_no = rand_no * 100;alert(rand_no);\">Click to get see the random number<\/a>.<\/p>\n<p>The code above will give us a random number between 0 and 100. All numbers will be a little more than 0 and a little less than 100 &#8211; and they still have the long tail of numbers after the decimal. The next step involves another method of the JavaScript <span class=\"codeword\">Math()<\/span> object called <span class=\"codeword\"><strong>ceil()<\/strong><\/span>.<\/p>\n<h2>JavaScript ceil() method<\/h2>\n<p>The JavaScript ceil() rounds a decimal number to the <strong><em>next higher integer<\/em><\/strong>. Thus,<\/p>\n<pre class=\"small-text\">\r\nMath.ceil(2.456)              \/\/gives 3\r\nMath.ceil(46.9)               \/\/gives 47\r\nMath.ceil(0.0006)             \/\/ gives 1\r\n<\/pre>\n<p>To remove numbers after the decimal and provide us with an integer between 1 and 100, we will pass the random number generated by <span class=\"codeword\">random()<\/span> to <span class=\"codeword\">ceil()<\/span>.<\/p>\n<pre class=\"small-text\">\r\nvar rand_no = Math.random();\r\nrand_no = rand_no * 100;\r\nrand_no = Math.ceil(rand_no);\r\nalert(rand_no);\r\n<\/pre>\n<p><a href=\"javascript:void(0)\" onclick=\"var rand_no = Math.random();rand_no = rand_no * 100;rand_no = Math.ceil(rand_no);alert(rand_no);\">Click to generate a random number between 1 and 100<\/a>.<br \/>The above set of statements can also be shortened to:<\/p>\n<pre class=\"small-text\">\r\nvar rand_no = Math.ceil(100*Math.random());\r\nalert(rand_no);\r\n<\/pre>\n<p>JavaScript generates random numbers based on a formula. In a sense this is not random because if you know the formula, you know which number will come up next. However, this works fine for the web applications you will develop.<\/p>\n<p><a href=\"javascript:void(0)\" onclick=\"var drn = '';var rand_no;for (x = 0; x &lt; 20; x++){rand_no = Math.ceil(100*Math.random());drn = drn + rand_no + '\\n';}alert(drn);&#13;&#10;\">Get a list of 20 randomly generated numbers between 1 and 100<\/a>.<\/p>\n<p><strong>What if you want random numbers between 0 and 10?<\/strong><br \/>The question is important. Because if we use the above code, it will simply not work. Since <span class=\"codeword\">ceil()<\/span> always returns the next higher integer, all random number that are between 0 and 1 will be converted to 1.<br \/>We will learn about another JavaScript method to solve this problem.<\/p>\n<h2>Math.floor() method<\/h2>\n<p>The <span class=\"codeword\">floor()<\/span> <strong>rounds a number down to the lower integer<\/strong>. Thus:<\/p>\n<pre class=\"small-text\">\r\nMath.floor(2.456)\t\t\/\/gives 2\r\nMath.floor(46.9)\t\t\/\/gives 46\r\nMath.floor(0.0006)\t\t\/\/ gives 0\r\nMath.floor(1.0006)\t\t\/\/ gives 1\r\nMath.floor(0.932)\t\t\/\/ gives 0\r\n<\/pre>\n<p>But this throws up another problem. Number between 0.9 and 1.0 will all be rounded down (after multiplying with 10) to 9!<br \/>The solution lies in multiplying the random number generated by <span class=\"codeword\">random()<\/span> with 11 &#8211; one number more than the range.<\/p>\n<pre class=\"small-text\">\r\nvar rand_no = Math.floor(11*Math.random());\r\nalert(rand_no);\r\n<\/pre>\n<p><a href=\"javascript:void()\" onclick=\"var drn = '';var rand_no;for (x = 0; x &lt; 20; x++){rand_no = Math.floor(11*Math.random());drn = drn + rand_no + '\\n';}alert(drn);\">List of 20 random number between 0 and 10<\/a>.<\/p>\n<h2>Random number from a given range<\/h2>\n<p>To generate random numbers from a given range, follow the steps below:<\/p>\n<ul class=\"withbullets\">\n<li>Get number between 0.0 and 1.0 from <span class=\"codeword\">random()<\/span> method.<\/li>\n<li>Multiply it with the difference of upper value and <em>one less than<\/em> the lower value of the range.<\/li>\n<li>Use <span class=\"codeword\">floor()<\/span> to convert it into an integer<\/li>\n<li>Add the lower value of the range<\/li>\n<\/ul>\n<pre class=\"small-text\">\r\nvar rand_no = Math.floor((10-4)*Math.random()) + 5;\r\nalert(rand_no);\r\n<\/pre>\n<p>The code above generates a random number between 5 and 10. Just to prove that this works beautifully <a href=\"javascript:void()\" onclick=\"var drn = '';var rand_no;for (x = 0; x &lt; 20; x++){rand_no = Math.floor((10-4)*Math.random()) + 5;drn = drn + rand_no + '\\n';}alert(drn);\">click to get a list of 20 random number between 5 and 10<\/a><\/p>\n<div class=\"pagenav\">\n<ul>\n<li><a href=\"\/\/www.webdevelopersnotes.com\/javascript-image-change-using-functions\" title=\"Image change using javascript functions\">&lt; Back<\/a><\/li>\n<li><a href=\"\/\/www.webdevelopersnotes.com\/javascript-tutorial\" title=\"JavaScript tutorial\">1<\/a><\/li>\n<li>&#8230;<\/li>\n<li><a href=\"\/\/www.webdevelopersnotes.com\/javascript-event-handlers-part-1\" title=\"Javascript onmouseover and javascript onmouseout event handlers\">10<\/a><\/li>\n<li>&#8230;<\/li>\n<li><a href=\"\/\/www.webdevelopersnotes.com\/javascript-if-statement\" title=\"Javascript IF statement\">20<\/a><\/li>\n<li>&#8230;<\/li>\n<li><a href=\"\/\/www.webdevelopersnotes.com\/changing-images-on-mouseover-using-javascript\" title=\"Changing images on mouseover using Javascript\">30<\/a><\/li>\n<li>&#8230;<\/li>\n<li><a href=\"\/\/www.webdevelopersnotes.com\/generating-random-numbers-in-javascript\" title=\"Generating random numbers in javascript\" class=\"thispage\">32<\/a><\/li>\n<li>&#8230;<\/li>\n<li><a href=\"\/\/www.webdevelopersnotes.com\/javascript-arrays-creating-and-storing-values\" title=\"Creating and storing values in Javascript arrays\">Next &gt;<\/a><\/li>\n<\/ul>\n<\/div>\n","protected":false},"excerpt":{"rendered":"To generate random numbers with JavaScript we employ the random() method of the Math object. It returns a floating-point number between 0.0 and 1.0.JavaScript Math object has several methods and we shall encounter three on this page &#8211; the first one being random(). var rand_no = Math.random(); alert(rand_no); In the code above, the random() method [&hellip;]","protected":false},"author":1,"featured_media":9544,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[56],"tags":[],"class_list":["post-4468","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-javascript"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/posts\/4468","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/comments?post=4468"}],"version-history":[{"count":0,"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/posts\/4468\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/media\/9544"}],"wp:attachment":[{"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/media?parent=4468"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/categories?post=4468"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.webdevelopersnotes.com\/wp-json\/wp\/v2\/tags?post=4468"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}