将范围舍入到步长值
我有一个这样的数字数组:
const dataset = [0.5, 2, 1, 93, 67.5, 1, 7, 34];
所以最小值为 0.5,最大值为 93。我想将该数据集的极值四舍五入为一个step值。
例如:
- 如果
step = 5结果应该是[0, 95] - 如果
step = 10结果应该是[0, 100]
新的最小值应该总是 <= 数据集中的实际最小值,新的最大值应该总是 >= 数据集中的实际最大值,它们都应该是 的倍数step。
注意:如果它也适用于负值,我应该很好。
我创建了该roundToNearest函数,但不足以解决我的问题:
function computeExtremisRounded(dataset: number[], step: number): [number, number] {
const [minValue, maxValue] = getMinAndMax(dataset) // suppose 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;
}
回答
您必须根据您是计算最大值还是最小值来设置上限或下限:
function computeExtremisRounded(dataset: number[], step: number): [number, number] {
const [minValue, maxValue] = getMinAndMax(dataset) // suppose it exists
const roundedMinValue = Math.floor(minValue / step) * step
const roundedMaxValue = Math.ceil(maxValue / step) * step
return [roundedMinValue, roundedMaxValue]
}