Skip to content

Instantly share code, notes, and snippets.

@vireshas
Forked from davidvthecoder/round.go
Created May 25, 2017 05:22
Show Gist options
  • Select an option

  • Save vireshas/b9407a102bb9ab3418b541f7c06be027 to your computer and use it in GitHub Desktop.

Select an option

Save vireshas/b9407a102bb9ab3418b541f7c06be027 to your computer and use it in GitHub Desktop.
Arggh Golang does not include a round function in the standard math package. So I wrote a quick one.
package main
import (
"log"
"math"
)
func Round(val float64, roundOn float64, places int ) (newVal float64) {
var round float64
pow := math.Pow(10, float64(places))
digit := pow * val
_, div := math.Modf(digit)
if div >= roundOn {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
newVal = round / pow
return
}
func main() {
log.Println(Round(123.555555, .5, 3))
log.Println(Round(123.558, .5, 2))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment