みさご解体新書

値を別の値単位で丸める

概要

2 つの値 A,B(0<B)A, B\thinspace(0 < B) を渡すと、A の値に近い B の倍数値を返す。

A が B の倍数なら、そのまま A を返すが、B の倍数でないなら、丸め処理を使用して近い倍数値を返す。

コード例

function floor(value: number, unit: number): number {
  return Math.floor(value / unit) * unit;
}

function ceil(value: number, unit: number): number {
  return Math.ceil(value / unit) * unit;
}
const unit = 3;
for (let i = -10; i <= 10; i++) {
  console.log(`floor(${i}, ${unit}) = ${floor(i, unit)}`);
}
for (let i = -10; i <= 10; i++) {
  console.log(`ceil(${i}, ${unit}) = ${ceil(i, unit)}`);
}
floor(-10, 3) = -12
floor(-9, 3) = -9
floor(-8, 3) = -9
floor(-7, 3) = -9
floor(-6, 3) = -6
floor(-5, 3) = -6
floor(-4, 3) = -6
floor(-3, 3) = -3
floor(-2, 3) = -3
floor(-1, 3) = -3
floor(0, 3) = 0
floor(1, 3) = 0
floor(2, 3) = 0
floor(3, 3) = 3
floor(4, 3) = 3
floor(5, 3) = 3
floor(6, 3) = 6
floor(7, 3) = 6
floor(8, 3) = 6
floor(9, 3) = 9
floor(10, 3) = 9

ceil(-10, 3) = -9
ceil(-9, 3) = -9
ceil(-8, 3) = -6
ceil(-7, 3) = -6
ceil(-6, 3) = -6
ceil(-5, 3) = -3
ceil(-4, 3) = -3
ceil(-3, 3) = -3
ceil(-2, 3) = 0
ceil(-1, 3) = 0
ceil(0, 3) = 0
ceil(1, 3) = 3
ceil(2, 3) = 3
ceil(3, 3) = 3
ceil(4, 3) = 6
ceil(5, 3) = 6
ceil(6, 3) = 6
ceil(7, 3) = 9
ceil(8, 3) = 9
ceil(9, 3) = 9
ceil(10, 3) = 12

下駄付きで丸める場合

const start = 5;
const interval = 6;

for (let i = 0; i < 13; i++) {
  if (i < start) {
    console.log(i, start);
  } else {
    console.log(i, ceil(i - start, interval) + start);
  }
}
0 5
1 5
2 5
3 5
4 5
5 5
6 11
7 11
8 11
9 11
10 11
11 11
12 17

下限が 0 でない場合の丸め方。

下限が 5 で、倍数値が 6 で丸める例。

ソースコード

TypeScript

app.ts

C++

a.cpp

解説/アルゴリズム

floor(左側にある一番近くの倍数値に丸める場合)

たとえば、 25 を 6 単位で丸める場合、 25 / 6 = 4.16... で割り切れない。

そこで、 4.16... の小数点以下を切り捨て、整数値 4 に変換する。

6 x 4 = 24 が 25 を 6 単位で左側に丸めた結果になる。

この関数は負の値でも動作し、たとえば、 -25 を 6 単位で丸めると -30 になる。

ceil(右側にある一番近くの倍数値に丸める場合)

たとえば、 25 を 6 単位で丸める場合、 25 / 6 = 4.16... で割り切れない。

そこで、 4.16... の小数点以下を切り上げ、整数値 5 に変換する。

6 x 5 = 30 が 25 を 6 単位で右側に丸めた結果になる。

この関数は負の値でも動作し、たとえば、 -25 を 6 単位で丸めると -24 になる。

内部で利用しているアルゴリズム

床関数, 天井関数, ROUND 関数