I have an array of numbers like this:
const dataset = [0.5, 2, 1, 93, 67.5, 1, 7, 34];
The minimum value is 0.5 and the maximum value is 93. I want to round the extremes of this dataset to a specified step
value.
For example:
- If
step = 5
, the result should be[0, 95]
- If
step = 10
, the result should be[0, 100]
The new minimum value should always be less than or equal to the actual minimum value in the dataset, and the new maximum value should always be greater than or equal to the real maximum value in the dataset. Both values should also be multiples of the specified step
.
Note: It would be great if this also works with negative values.
I've created a function called roundToNearest
, but it's not enough to solve my problem:
function computeExtremisRounded(dataset: number[], step: number): [number, number] {
const [minValue, maxValue] = getMinAndMax(dataset) // assuming it exists
const roundedMinValue = roundToNearest(minValue, step)
const roundedMaxValue = roundToNearest(maxValue, step)
return [roundedMinValue, roundedMaxValue]
}
function roundToNearest(value: number, step: number): number {
return Math.round(value / step) * step;
}