Get a random number between 0.0200 and 0.120 (float numbers)
JavascriptJavascript Problem Overview
I need to create a random number between 0.0200 and 0.120 using JavaScript. How would I do this?
Javascript Solutions
Solution 1 - Javascript
You could use
(Math.random() * (0.120 - 0.0200) + 0.0200).toFixed(4)
toFixed(n) is used to convert a number into a string, keeping only the "n" decimals.
Hope it helps ^_^
Solution 2 - Javascript
Here you are:
function generateRandomNumber() {
var min = 0.0200,
max = 0.120,
highlightedNumber = Math.random() * (max - min) + min;
alert(highlightedNumber);
};
generateRandomNumber();
I understand your real question — you do not know how to get a random number between floating numbers, right? By the way, the answer is passed before.
To play with the code, just click here to jsFiddle.
Update
To get the four first numbers of your decimal, use .toFixed(3)
method. I've performed an example here, on jsFiddle.
Solution 3 - Javascript
If you're looking to generate that and other random numbers or things, I'd suggest taking a look the Chance library. It provides a nice abstraction layer so you don't have to fiddle with Math.random() and write your own.
chance.floating({min: 0.02, max: 0.12});
Full disclosure: I'm the author so I'm a bit biased :)
Also, if this is the only random thing you need to generate or it's client-side where size is a real issue, I'd suggest just using one of the suggestions above. Not worth a few Kb where a couple lines will do.