Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

randomFloatInRange

Generates a random floating-point number between min (inclusive) and max (exclusive).

TypeScript
Copied!
1/**
2 * Generates a random floating-point number between min (inclusive) and max (exclusive).
3 *
4 * @param min - Minimum value (inclusive).
5 * @param max - Maximum value (exclusive).
6 * @returns A random float between min and max.
7 */
8export function randomFloatInRange(min: number, max: number): number {
9  return Math.random() * (max - min) + min;
10}
  • Exclusive Upper Bound

    Mimics typical Math.random() behavior with an inclusive lower and exclusive upper bound, making it ideal for intervals.

  • Compact and Efficient

    Uses native arithmetic with no conditionals or loops, ensuring high performance.

  • Predictable and Reusable

    Stateless and deterministic given the same random seed (if seeded externally), allowing for repeatable testing with mocks.

  • Supports Full Range of Floats

    Generates any floating-point value within the specified bounds, not limited to integers or fixed steps.

Tests | Examples

TypeScript
Copied!
1test('randomFloatInRange - basic range', () => {
2  const value = randomFloatInRange(1, 5);
3  expect(value).toBeGreaterThanOrEqual(1);
4  expect(value).toBeLessThan(5);
5});
6
7test('randomFloatInRange - negative range', () => {
8  const value = randomFloatInRange(-10, -5);
9  expect(value).toBeGreaterThanOrEqual(-10);
10  expect(value).toBeLessThan(-5);
11});
12
13test('randomFloatInRange - min and max very close', () => {
14  const value = randomFloatInRange(0.999, 1);
15  expect(value).toBeGreaterThanOrEqual(0.999);
16  expect(value).toBeLessThan(1);
17});
18
19test('randomFloatInRange - edge case: min == max', () => {
20  const result = () => randomFloatInRange(2, 2);
21  expect(result).not.toThrow(); // it will return NaN, which is acceptable in undefined case
22  expect(Number.isNaN(result())).toBe(true);
23});

Common Use Cases

  • Game Development

    Generate random positions, velocities, or variation in animations and effects.

  • Statistical Sampling

    Create continuous-value simulations or probabilistic models.

  • UI Randomization

    Add slight randomness to layout, timing, or motion effects for more natural results.

  • Testing and Benchmarking

    Simulate random input values to test performance or accuracy of numerical algorithms.

  • Procedural Content Generation

    Use floating-point randomness in generation of terrain, audio, or visual elements.

Codebase: Utilities -> Numbers -> randomFloatInRange | Yevhen Klymentiev