Math.round Rounds Halves Toward Infinity

Compare Math.round, trunc, floor, and ceil on negatives and halves: round sends every .5 toward positive infinity, trunc cuts, floor and ceil pull apart.

JavascriptData Integrity

Code

javascriptsnippet
19 lines
// 四个舍入函数在负数与 .5 上的行为各不相同
for (const n of [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]) {
  console.log(
    n,
    'round=' + Math.round(n),
    'trunc=' + Math.trunc(n),
    'floor=' + Math.floor(n),
    'ceil=' + Math.ceil(n),
  );
}

// round 对 .5 一律向 +Infinity:-0.5 得 -0,不是 -1
console.log('round(-0.5) is -0:', Object.is(Math.round(-0.5), -0));

// trunc 直接砍掉小数部分,正负对称
console.log('trunc symmetric:', Math.trunc(-4.7) === -4 && Math.trunc(4.7) === 4);

// floor 向 -Infinity、ceil 向 +Infinity,方向相反
console.log('floor vs ceil:', Math.floor(-0.1), Math.ceil(-0.1));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

-2.5 round=-2 trunc=-2 floor=-3 ceil=-2
-1.5 round=-1 trunc=-1 floor=-2 ceil=-1
-0.5 round=0 trunc=0 floor=-1 ceil=0
0.5 round=1 trunc=0 floor=0 ceil=1
1.5 round=2 trunc=1 floor=1 ceil=2
2.5 round=3 trunc=2 floor=2 ceil=3
round(-0.5) is -0: true
trunc symmetric: true
floor vs ceil: -1 -0

How the snippet works

Repetition is confined to for (const n of [-2.5, -1.5, -0.5, 0.5, 1.5, 2.5]) — the rest of the file is straight-line.

Where the applying happens

Running the file prints labeled results such as round(-0.5) is -0:, trunc symmetric:, floor vs ceil: — each operation’s effect is visible in the output.

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install.