Last active
July 8, 2017 22:01
-
-
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
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 ( | |
"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