Compare Rounding Functions On Negatives

Round, RoundToEven, Floor, Ceil, and Trunc disagree most on negative halves; this table shows each function's rule side by side.

GoData Integrity

Code

gosnippet
21 lines
package main

import (
	"fmt"
	"math"
)

func main() {
	values := []float64{-2.5, -1.5, 1.5, 2.5}

	fmt.Println("value   round roundeven  floor   ceil   trunc")
	for _, v := range values {
		fmt.Printf("%5.1f  %5.1f  %9.1f  %5.1f  %5.1f  %5.1f\n",
			v,
			math.Round(v),        // 离零更远的整数:-2.5 -> -3
			math.RoundToEven(v),  // 半数向偶:-2.5 -> -2(银行家舍入)
			math.Floor(v),        // 向负无穷:-2.5 -> -3
			math.Ceil(v),         // 向正无穷:-2.5 -> -2
			math.Trunc(v))        // 向零截断:-2.5 -> -2
	}
}

Five functions, one table

The program iterates over -2.5, -1.5, 1.5, and 2.5 and prints each through math.Round, math.RoundToEven, math.Floor, math.Ceil, and math.Trunc in a fixed-width table, so the disagreements line up row by row.

The negative-half split

On the halves, Round moves away from zero (-2.5 becomes -3), RoundToEven picks the even neighbor (-2.5 becomes -2, banker’s rounding), Floor goes to negative infinity (-3), Ceil goes to positive infinity (-2), and Trunc drops the fraction toward zero (-2). Positive halves show the mirror image.

Where this matters

Billing and averaging code that assumes “round half up” silently diverges on negatives; picking the function deliberately prevents that drift.

Interactive Tools for This Topic

FAQ

What rule does RoundToEven follow?
It rounds ties to the nearest even integer: -2.5 becomes -2 and -1.5 also becomes -2, which keeps long-run sums unbiased.
Where do Floor and Trunc disagree?
Only on negative non-integers: Floor moves to negative infinity while Trunc moves toward zero, so Floor(-2.5) is -3 and Trunc(-2.5) is -2.