← Home

Rounding in Go

I noticed that Go’s standard library doesn’t have a math.Round function, which was a bit of a surprise when I was implementing some functions which needed to give results to a number of decimal places.

Every now now and again, someone asks for a solution, and gets given a raft of solutions, from using the string formatting features of Go (not great performance if that matters), to adding 0.5 and flooring (the rounding to positive infinity algorithm).

No-one provided any unit tests or a description of the type of rounding they’d implemented, so I wrote up a package which does:

My package implements “Away From Zero” rounding and “To Even” rounding. It’s available at [0]

import "github.com/a-h/round"

func main() {
    fmt.Println(round.ToEven(float64(-3.5), 0)) // -4
    fmt.Println(round.ToEven(float64(-2.5), 0)) // -2
    fmt.Println(round.ToEven(float64(-1.5), 0)) // -2
    fmt.Println(round.ToEven(float64(-1.49), 0)) // -1
}