As far as I understand, you can generate a random number in JavaScript within a range using this function:
function getRandomInt (min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; }
Courtesy of IonuΕ£ G. Stan here .
What I want to know is that you can generate the best random number in a range using crypto.getRandomValues ββ() instead of Math. randomly(). I would like to be able to generate a number from 0 to 10 inclusive, or 0 - 1, or even 10 - 5000 inclusive.
You will notice that Math.random () creates a number like: 0.8565239671015732 .
The getRandomValues ββAPI might return something like:
- 231 with
Uint8Array(1) - 54328 with
Uint16Array(1) - 355282741 with
Uint32Array(1) .
So, how do I translate this back to decimal so that I can stick to the same range algorithm above? Or do I need a new algorithm?
Here is the code I tried, but it does not work too well.
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; }
At the lower end (range 0 - 1), it returns more than 0 than 1. What is the best way to do this with getRandomValues ββ()?
Many thanks
javascript random cryptography range
user2503552
source share