Created
February 23, 2016 20:34
-
-
Save lmas/f0346fce86d56b5c62ff to your computer and use it in GitHub Desktop.
round.go - Round a float64 in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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