title: Javascript: Generate a random number within a range using crypto.getRandomValues
body: <p>I understand you can generate a random number in JavaScript within a range using this function:</p>
  
  <pre><code>function getRandomInt (min, max) {
      return Math.floor(Math.random() * (max - min + 1)) + min;
  }
  </code></pre>
  
  <p>Courtesy of <em>Ionuț G. Stan</em> <a href="https://stackoverflow.com/a/1527820">here</a>.</p>
  
  <p>What I want to know is if you can generate a <em>better</em> random number in a range using <a href="https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues" rel="noreferrer">crypto.getRandomValues()</a> instead of Math.random(). I would like to be able to generate a number between 0 and 10 inclusive, or 0 - 1, or even 10 - 5000 inclusive.</p>
  
  <p>You'll note Math.random() produces a number like: <strong>0.8565239671015732</strong>.</p>
  
  <p>The getRandomValues API might return something like:</p>
  
  <ul>
  <li><strong>231</strong>  with <code>Uint8Array(1)</code></li>
  <li><strong>54328</strong> with <code>Uint16Array(1)</code></li>
  <li><strong>355282741</strong> with <code>Uint32Array(1)</code>.</li>
  </ul>
  
  <p>So how to translate that back to a decimal number so I can keep with the same range algorithm above? Or do I need a new algorithm?</p>
  
  <p>Here's the code I tried but it doesn't work too well.</p>
  
  <pre><code>function getRandomInt(min, max) {       
      // Create byte array and fill with 1 random number
      var byteArray = new Uint8Array(1);
      window.crypto.getRandomValues(byteArray);
  
      // Convert to decimal
      var randomNum = '0.' + byteArray[0].toString();
  
      // Get number in range
      randomNum = Math.floor(randomNum * (max - min + 1)) + min;
  
      return randomNum;
  }
  </code></pre>
  
  <p>At the low end (range 0 - 1) it returns more 0's than 1's. What's the best way to do it with getRandomValues()?</p>
  
  <p>Many thanks</p>