EMZETT.
Login

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

LanguageDie 1–6Round down
JavaScriptMath.floor(Math.random()*6)+1Math.floor(x)
Javanew Random().nextInt(6)+1 or ThreadLocalRandom.current().nextInt(1,7)Math.floor(x)
Pythonrandom.randint(1,6)math.floor(x)
Crand() % 6 + 1 (call srand(time(0)) first)floor(x) from math.h
C++std::uniform_int_distribution<int>(1,6) with mt19937std::floor(x)
C#Random.Shared.Next(1,7)Math.Floor(x)
Gorand.IntN(6)+1 (math/rand/v2)math.Floor(x)
Rustrng.gen_range(1..=6) (rand crate)x.floor()
PHPrandom_int(1,6)floor($x)
Rubyrand(1..6)x.floor
Kotlin(1..6).random()floor(x)
SwiftInt.random(in: 1...6)x.rounded(.down)
SQLFLOOR(RAND()*6)+1 (MySQL)FLOOR(x)
Bash$((RANDOM % 6 + 1))integer division
  • Secure: Python secrets, Java SecureRandom, JS crypto.getRandomValues, C# RandomNumberGenerator, PHP random_int, Go crypto/rand.
  • Modulo trap: rand() % n is 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