Numbers
number: Math.round は負の 0.5 をゼロ方向へ丸める
Math.round の半端値処理は、常にゼロから遠ざける丸めではありません。
SourceroundingModes.ts
Node.js 22
export function halfAwayFromZero(value: number): number {
return value < 0 ? -Math.round(-value) : Math.round(value);
}TestroundingModes.test.ts
Node.js 22
import assert from "node:assert/strict";
import test from "node:test";
import { halfAwayFromZero } from "../../src/numbers/roundingModes.js";
test("MathRoundの負の半端値はゼロ方向になる", () => {
assert.equal(Math.round(1.5), 2);
assert.equal(Math.round(-1.5), -1);
assert.equal(halfAwayFromZero(-1.5), -2);
});01Assertion
このテストで確認できること
- Math.round(1.5) は 2 を返す
- Math.round(-1.5) は -1 を返す
- 要件に応じて丸め関数を明示できる
丸め方向は業務ルールです。負値を含む場合は標準 API の挙動を確認し、要件に合う関数を選びます。
OBSERVED RESULT
expected: Math.round(-1.5) → -1
actual: -1
expected: halfAwayFromZero(-1.5) → -2