Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@DavidVaini
Created April 9, 2014 19:58
Show Gist options
  • Star 71 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save DavidVaini/10308388 to your computer and use it in GitHub Desktop.
Save DavidVaini/10308388 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))
}
@DavidVaini
Copy link
Author

hi guys, I never saw these comments until just now. The implementation was old and was something quick and dirty. Thus the code is in a gist snippet and not a repo. This worked for my case which was positive integers, but note it will fail with negative numbers. It looks like people have other implementations though they don't account for what decimal place you want to round on or what value you want to round on (.5 vs .9 or other use cases.

@fedir
Copy link

fedir commented Feb 26, 2018

@korya +1

@blaskovicz
Copy link

@CamilleFrazaoCDP
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment