Round float to integer value

yourbasic.org/golang

Round away from zeroGo 1.10

Use math.Round to return the nearest integer, as a float64, rounding ties away from zero.

fmt.Println(math.Round(-0.6)) // -1
fmt.Println(math.Round(-0.4)) // -0
fmt.Println(math.Round(0.4))  // 0
fmt.Println(math.Round(0.6))  // 1

Note the special cases.

Round(±0) = ±0
Round(±Inf) = ±Inf
Round(NaN) = NaN

Round to even numberGo 1.10

Use math.RoundToEven to return the nearest integer, as a float64, rounding ties to an even number.

fmt.Println(math.RoundToEven(0.5)) // 0
fmt.Println(math.RoundToEven(1.5)) // 2

Convert to an int type

Note that when converting a floating-point number to an int type, the fraction is discarded (truncation towards zero).

fmt.Println(int64(1.9))  //  1
fmt.Println(int64(-1.9)) // -1
Warning: If the result type cannot represent the value the conversion succeeds but the result is implementation-dependent.

Before Go 1.10

The following implementations are equivalent to math.Round and math.RoundToEven, but less efficient.

// Round returns the nearest integer, rounding ties away from zero.
func Round(x float64) float64 {
	t := math.Trunc(x)
	if math.Abs(x-t) >= 0.5 {
		return t + math.Copysign(1, x)
	}
	return t
}
// RoundToEven returns the nearest integer, rounding ties to an even number.
func RoundToEven(x float64) float64 {
	t := math.Trunc(x)
	odd := math.Remainder(t, 2) != 0
	if d := math.Abs(x - t); d > 0.5 || (d == 0.5 && odd) {
		return t + math.Copysign(1, x)
	}
	return t
}

More code examples

Go blueprints: code for com­mon tasks is a collection of handy code examples.

Share this page: