Skip to content

Instantly share code, notes, and snippets.

@lmas
Created February 23, 2016 20:34
Show Gist options
  • Save lmas/f0346fce86d56b5c62ff to your computer and use it in GitHub Desktop.
Save lmas/f0346fce86d56b5c62ff to your computer and use it in GitHub Desktop.
round.go - Round a float64 in Go
package main
func RoundPrec(x float64, prec int) float64 {
if math.IsNaN(x) || math.IsInf(x, 0) {
return x
}
sign := 1.0
if x < 0 {
sign = -1
x *= -1
}
var rounder float64
pow := math.Pow(10, float64(prec))
intermed := x * pow
_, frac := math.Modf(intermed)
if frac >= 0.5 {
rounder = math.Ceil(intermed)
} else {
rounder = math.Floor(intermed)
}
return rounder / pow * sign
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment