Get a random number between 0.0200 and 0.120 (float numbers) [duplicate]

I need to create a random number between 0.0200 and 0.120 using JavaScript. How would I do this?



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 ^_^


Here you are:

function generateRandomNumber() {
    var min = 0.0200,
        max = 0.120,
        highlightedNumber = Math.random() * (max - min) + min;



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.


To get the four first numbers of your decimal, use .toFixed(3) method. I've performed an example here, on jsFiddle.


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.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.