Skip to content

Instantly share code, notes, and snippets.

@alextanhongpin
Last active September 9, 2017 02:02
Show Gist options
  • Save alextanhongpin/e92b18a62f097e488cb29c83b0401723 to your computer and use it in GitHub Desktop.
Save alextanhongpin/e92b18a62f097e488cb29c83b0401723 to your computer and use it in GitHub Desktop.
// This program demonstrates how to round numbers in golang
package main
import (
"log"
"math"
)
// func round(val float64) float64 {
// _, v := math.Modf(val)
// if math.Abs(v) >= .5 {
// if val >= 0 {
// return math.Ceil(val)
// }
// return math.Floor(val)
// }
// if val >= 0 {
// return math.Floor(val)
// }
// return math.Ceil(val)
// }
// If you just need to round it up to the nearest integer, this should be sufficient.
// Thanks to angch for the tips
func round(val float64) float64 {
return math.Floor(val + 0.5)
}
func main() {
log.Println(round(123.54))
log.Println(round(-100.4))
log.Println(round(-0.4))
log.Println(round(-0.5))
log.Println(round(0.5))
log.Println(round(0.4))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment