Created
September 3, 2015 12:31
-
-
Save siddontang/1806573b9a8574989ccb to your computer and use it in GitHub Desktop.
round implementation in go
This file contains hidden or 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
package main | |
import "fmt" | |
import "math" | |
// see http://www.gnu.org/software/libc/manual/html_node/Rounding.html | |
func rint(x float64) float64 { | |
v, frac := math.Modf(x) | |
if x > 0.0 { | |
if frac > 0.5 || (frac == 0.5 && uint64(v)%2 != 0) { | |
v += 1.0 | |
} | |
} else { | |
if frac < -0.5 || (frac == -0.5 && uint64(v)%2 != 0) { | |
v -= 1.0 | |
} | |
} | |
return v | |
} | |
func main() { | |
fmt.Println("Hello, playground") | |
fmt.Printf("%f\n", rint(1.5)) | |
fmt.Printf("%f\n", rint(2.5)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment