Skip to content

Instantly share code, notes, and snippets.

@countlurk
Last active July 8, 2017 22:01
Show Gist options
  • Save countlurk/1ed54cdd83163e6c609d9b4eecac6f18 to your computer and use it in GitHub Desktop.
Save countlurk/1ed54cdd83163e6c609d9b4eecac6f18 to your computer and use it in GitHub Desktop.
A function that rounds floats in Golang. Functionally equivalent to round() in Python 2 (rounds away from zero). Test it out here: https://play.golang.org/p/UpjhU7yXsc
package main
import (
"math"
)
func roundFloat(num float64, precision float64) float64 {
var power float64
var mod float64
var negative bool
if num < 0 {
negative = true
num = -1 * num
}
power = math.Pow(10, precision)
num = num * power
mod = math.Mod(num, 1)
num -= mod
if mod >= .5 {
num += 1
}
num = num / power
if negative {
num = -1 * num
}
return num
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment