-- Leo's gemini proxy

-- Connecting to capsule.adrianhesketh.com:1965...

-- Connected

-- Sending request

-- Meta line: 20 text/gemini; charset=utf-8

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

-- Response ended

-- Page fetched on Sun Apr 28 07:10:25 2024