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 https://github.com/a-h/round/

Advertisements