Random and rounding in many programming languages
In short: Almost every language has a function for random numbers and one for rounding down. Names and behaviour differ in detail.
In more detail: The table shows how to write a random number from 1 to 6 and rounding down in common languages. Security-relevant random values always need the cryptographic generator of the respective language.
In detail
| Language | Die 1–6 | Round down |
|---|---|---|
| JavaScript | Math.floor(Math.random()*6)+1 | Math.floor(x) |
| Java | new Random().nextInt(6)+1 or ThreadLocalRandom.current().nextInt(1,7) | Math.floor(x) |
| Python | random.randint(1,6) | math.floor(x) |
| C | rand() % 6 + 1 (call srand(time(0)) first) | floor(x) from math.h |
| C++ | std::uniform_int_distribution<int>(1,6) with mt19937 | std::floor(x) |
| C# | Random.Shared.Next(1,7) | Math.Floor(x) |
| Go | rand.IntN(6)+1 (math/rand/v2) | math.Floor(x) |
| Rust | rng.gen_range(1..=6) (rand crate) | x.floor() |
| PHP | random_int(1,6) | floor($x) |
| Ruby | rand(1..6) | x.floor |
| Kotlin | (1..6).random() | floor(x) |
| Swift | Int.random(in: 1...6) | x.rounded(.down) |
| SQL | FLOOR(RAND()*6)+1 (MySQL) | FLOOR(x) |
| Bash | $((RANDOM % 6 + 1)) | integer division |
- Secure: Python
secrets, JavaSecureRandom, JScrypto.getRandomValues, C#RandomNumberGenerator, PHPrandom_int, Gocrypto/rand. - Modulo trap:
rand() % nis slightly biased when the number range is not divisible by n. - Seed: the same start value (seed) gives the same sequence, useful for tests.
See also: Math.random and Math.floor, Random numbers: pseudo-random and true random