Skip to content

Instantly share code, notes, and snippets.

@siddontang siddontang/rint.go
Created Sep 3, 2015

Embed
What would you like to do?
round implementation in go
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
You can’t perform that action at this time.