Skip to content

floorToStep function ​

Rounds a number down to a multiple of a step, without float noise.

ts
import { floorToStep } from 'utils';

Signature ​

ts
export function floorToStep(value: number, step = 1): number

Parameters ​

NameDescription
valueThe number to round down.
stepThe step, a positive number. Defaults to 1.

Returns ​

The largest multiple of step lower than or equal to value.

Example ​

ts
floorToStep(0.39, 0.1); // 0.3
floorToStep(-7, 5); // -10

Tests ​

Line coverage: 100 %.

  • ✅ floors 0.3 to step 0.1 as 0.3
  • ✅ floors 0.39 to step 0.1 as 0.3
  • ✅ floors 7 to step 5 as 5
  • ✅ floors -7 to step 5 as -10
  • ✅ floors 0.7 to step 0.1 as 0.7
  • ✅ takes the defaults

Source ​

src/math/floor-to-step.ts (on GitHub)

Files it needs ​

src/math/floor-to-step.ts imports, directly or not:

Source code
ts
import { snapToStep } from './internal';

/**
 * Rounds a number down to a multiple of a step, without float noise.
 *
 * @param value - The number to round down.
 * @param step - The step, a positive number. Defaults to `1`.
 * @returns The largest multiple of `step` lower than or equal to `value`.
 * @example
 * floorToStep(0.39, 0.1); // 0.3
 * floorToStep(-7, 5); // -10
 */
export function floorToStep(value: number, step = 1): number {
  return snapToStep(value, step, Math.floor);
}
Test file
ts
import { floorToStep } from './floor-to-step';

describe(floorToStep, () => {
  it.for([
    [0.3, 0.1, 0.3],
    [0.39, 0.1, 0.3],
    [7, 5, 5],
    [-7, 5, -10],
    [0.7, 0.1, 0.7],
  ] as const)('floors %s to step %s as %s', ([value, step, expected]) => {
    expect(floorToStep(value, step)).toBe(expected);
  });

  it('takes the defaults', () => {
    expect(floorToStep(2.7)).toStrictEqual(floorToStep(2.7, 1));
  });
});

Keywords: floor, to, step, math, function

Generated from the JSDoc of the sources.