💾 Archived View for capsule.adrianhesketh.com › 2017 › 04 › 14 › rounding-in-go captured on 2023-04-19 at 23:04:56. Gemini links have been rewritten to link to archived content

View Raw

More Information

⬅️ Previous capture (2021-11-30)

-=-=-=-=-=-=-

capsule.adrianhesketh.com

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]

[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
}

More

Next

Completing the Udacity Linear Algebra Course in Go

Previous

Getting line and character positions from Go's JSON unmarshal errors

Home

home