Skip to content

Instantly share code, notes, and snippets.

@yoander
Forked from pelegm/round.go
Created December 15, 2017 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoander/04416c10a6a3f8b0f9a6d4a50b92af17 to your computer and use it in GitHub Desktop.
Save yoander/04416c10a6a3f8b0f9a6d4a50b92af17 to your computer and use it in GitHub Desktop.
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)
_div := math.Copysign(div, val)
_roundOn := math.Copysign(roundOn, val)
if _div >= _roundOn {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
newVal = round / pow
return
}
func main() {
log.Println(Round(7.503300000000001e-05, .5, 5))
log.Println(Round(-7.503300000000001e-05, .5, 5))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment