-
-
Save alextanhongpin/e92b18a62f097e488cb29c83b0401723 to your computer and use it in GitHub Desktop.
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
// 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