Skip to content

Instantly share code, notes, and snippets.

@siddontang
Created September 3, 2015 12:31
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siddontang/1806573b9a8574989ccb to your computer and use it in GitHub Desktop.
Save siddontang/1806573b9a8574989ccb to your computer and use it in GitHub Desktop.
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