Go: Round float to integer value

Round away from zero

Use math.Round, which will be introduced in Go 1.10, to return the nearest integer, rounding ties away from zero.

for _, x := range []float64{-0.6, -0.4, 0.4, 0.6} {
        fmt.Println(math.Round(x))
}
-1
-0
0
1

Note the special cases:

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

Round to an even number

Use math.RoundToEven, which will be introduced in Go 1.10, to return the nearest integer, rounding ties to an even number.

fmt.Println(math.RoundToEven(0.5), math.RoundToEven(1.5))
// Output: 0 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):

var f float64 = 1.9
n := int64(f) //  1
n = int64(-f) // -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
}

Comments

Be the first to comment!