How to generate a random number in JavaScript
Generating random numbers is fundamental for games, animations, data sampling, color generation, and probabilistic UI behavior in JavaScript applications.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve used Math.random() extensively in chart demos, color pickers, and interactive examples.
The built-in Math.random() function is the foundation for all client-side random number generation — simple, universally supported, and sufficient for most UI use cases.
For integers specifically, see how to generate a random integer in JavaScript.
Use Math.random() to generate a pseudorandom floating-point number between 0 (inclusive) and 1 (exclusive).
Math.random()
// e.g. 0.7834592847362841
Every call returns a new float in [0, 1). Multiply, shift, and round as needed to fit your range.
1. Basic Float Between 0 and 1
Math.random() on its own produces a float like 0.312 or 0.987. This is useful for probability checks and weighted decisions.
const roll = Math.random()
if (roll < 0.1) {
console.log('10% chance — rare event triggered')
} else if (roll < 0.5) {
console.log('40% chance — common event')
} else {
console.log('50% chance — default path')
}
2. Random Float in a Specific Range
To generate a float between min and max, scale and shift the result.
const randomInRange = (min, max) => Math.random() * (max - min) + min
randomInRange(0, 10) // e.g. 7.42 — float between 0 and 10
randomInRange(1.5, 3.5) // e.g. 2.18 — float between 1.5 and 3.5
randomInRange(-1, 1) // e.g. -0.34 — useful for offsets or jitter
Note: unlike the integer version, max is exclusive here since Math.random() never reaches 1.
3. Controlling Decimal Precision
Raw Math.random() output has many decimal places. Round to the precision you need with toFixed() or arithmetic.
const twoDecimals = parseFloat((Math.random() * 100).toFixed(2))
// e.g. 47.83
const oneDecimal = Math.round(Math.random() * 10 * 10) / 10
// e.g. 6.3
// Percentage display
const percentage = (Math.random() * 100).toFixed(1) + '%'
// e.g. '73.4%'
Use toFixed() for display strings, and arithmetic rounding when you need a true number for calculations. See how to round a number in JavaScript for a full comparison of rounding strategies.
4. Generating a Random Color
A common UI use case is generating random hex or RGB colors for chart datasets, avatars, or placeholder backgrounds.
// Random hex color
const randomHex = () => '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0')
randomHex() // e.g. '#a3f2c1'
// Random RGB color
const randomRgb = () => {
const r = Math.floor(Math.random() * 256)
const g = Math.floor(Math.random() * 256)
const b = Math.floor(Math.random() * 256)
return `rgb(${r}, ${g}, ${b})`
}
randomRgb() // e.g. 'rgb(120, 45, 200)'
These are handy for populating CoreUI chart datasets with distinct series colors or generating unique badge backgrounds in demo UIs.
5. Seeded / Reproducible Randomness
Math.random() cannot be seeded — each run produces different results. When you need reproducible sequences (e.g. for tests or procedural generation), implement a simple seeded PRNG.
function seededRandom(seed) {
let s = seed
return function () {
s = (s * 9301 + 49297) % 233280
return s / 233280
}
}
const rand = seededRandom(42)
rand() // always 0.17605633802816902 for seed 42
rand() // always 0.6561124694376528
This is a simple linear congruential generator — good enough for deterministic test data, not for security.
6. Cryptographically Secure Random Numbers
Math.random() is a pseudorandom number generator and must not be used for security-sensitive values such as tokens, session IDs, or OTPs. Use the Web Crypto API instead.
// Secure float in [0, 1)
function secureRandom() {
const arr = new Uint32Array(1)
crypto.getRandomValues(arr)
return arr[0] / (0xffffffff + 1)
}
secureRandom() // cryptographically secure float
// Secure UUID
crypto.randomUUID() // e.g. '110e8400-e29b-41d4-a716-446655440000'
crypto.getRandomValues() is available in all modern browsers and Node.js 15+.
Best Practice Note:
Use Math.random() freely for UI, animations, games, and demo data — it is fast and universally supported.
For security-sensitive use cases (tokens, codes, IDs), always use crypto.getRandomValues() or crypto.randomUUID().
When you need whole numbers, combine Math.random() with Math.floor() as described in how to generate a random integer in JavaScript.



