Is it possible to generate a random decimal number in javascript?
ChicagoMadeFan
2010-11-01 17:05:31 UTC
I know how to generate a random integer but need to generatea number with a decimal
Four answers:
Ratchetr
2010-11-01 17:22:13 UTC
Math.random() generates a decimal number between 0 and 1.
If you want a different range, multiply and add.
If you paste this in your browser address bar and load it, it will generate a random decimal number between 100 and 200:
javascript:alert(100 + Math.random()*100)
hames
2016-10-20 02:03:06 UTC
Generate Random Number In Javascript
green meklar
2010-11-01 21:17:32 UTC
Math.random() already gives a pseudorandom number from 0 to 1.
To get a random floating point number within a certain range, first define the range by 'min' and 'max', then do this:
min + (Math.random() * (max - min))
Note however that this will never generate the maximum value. It may come extremely close, but the maximum value will never be generated.
If you need it to be possible to generate the maximum value, or you need more randomness than the built-in pseudorandom generator can provide, there are ways to construct more advanced systems that reduce weaknesses like that. However, they will also take longer to run.
flood
2010-11-01 17:10:18 UTC
could you not just cast the integer to a data type that holds a decimal and then say divide by ten
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.