roundToStep function
Rounds a number to the nearest multiple of a step, without float noise: roundToStep(0.3, 0.1) is 0.3.
ts
import { roundToStep } from 'utils';Signature
ts
export function roundToStep(value: number, step = 1): numberParameters
| Name | Description |
|---|---|
value | The number to round. |
step | The step, a positive number such as 0.1, 0.25 or 5. Defaults to 1. |
Returns
The nearest multiple of step, with no more decimals than step.
Example
ts
roundToStep(0.29, 0.1); // 0.3
roundToStep(8, 5); // 10Tests
Line coverage: 100 %.
- ✅ rounds 0.3 to step 0.1 as 0.3
- ✅ rounds 0.29 to step 0.1 as 0.3
- ✅ rounds 7 to step 5 as 5
- ✅ rounds 8 to step 5 as 10
- ✅ rounds -7 to step 5 as -5
- ✅ rounds 1.23456 to step 0.25 as 1.25
- ✅ rounds 3.7e-7 to step 1e-7 as 4e-7
- ✅ rounds 0.7 to step 0.1 as 0.7
- ✅ rounds 0.44 to step 0.30000000000000004 as 0.3
- ✅ rounds 1.23456 to step 1e-100 as 1.23456
- ✅ takes the defaults
Source
src/math/round-to-step.ts (on GitHub)
Files it needs
src/math/round-to-step.ts imports, directly or not:
Source code
ts
import { snapToStep } from './internal';
/**
* Rounds a number to the nearest multiple of a step, without float noise: `roundToStep(0.3, 0.1)` is `0.3`.
*
* @param value - The number to round.
* @param step - The step, a positive number such as `0.1`, `0.25` or `5`. Defaults to `1`.
* @returns The nearest multiple of `step`, with no more decimals than `step`.
* @example
* roundToStep(0.29, 0.1); // 0.3
* roundToStep(8, 5); // 10
*/
export function roundToStep(value: number, step = 1): number {
return snapToStep(value, step, Math.round);
}Test file
ts
import { roundToStep } from './round-to-step';
describe(roundToStep, () => {
it.for([
[0.3, 0.1, 0.3],
[0.29, 0.1, 0.3],
[7, 5, 5],
[8, 5, 10],
[-7, 5, -5],
[1.23456, 0.25, 1.25],
[0.00000037, 1e-7, 0.0000004],
[0.7, 0.1, 0.7],
[0.44, 0.1 + 0.2, 0.3],
[1.23456, 1e-100, 1.23456],
] as const)('rounds %s to step %s as %s', ([value, step, expected]) => {
expect(roundToStep(value, step)).toBe(expected);
});
it('takes the defaults', () => {
expect(roundToStep(2.5)).toStrictEqual(roundToStep(2.5, 1));
});
});Keywords: round, to, step, math, function