Skip to content

Instantly share code, notes, and snippets.

@GimmyHchs
Last active August 8, 2019 10:31
Show Gist options
  • Save GimmyHchs/839438f9e3147c772a0d098526d69d16 to your computer and use it in GitHub Desktop.
Save GimmyHchs/839438f9e3147c772a0d098526d69d16 to your computer and use it in GitHub Desktop.
[Golang Float Tricks] golang float tricks #go
package main
import (
"fmt"
"math"
)
func main() {
var a, b, c, d float64
a = 10.000000000000001
b = 9.99999999999999
c = 61.599999999999994
d = 61.600000000000006
fmt.Println(ToFixed(a, 2))
fmt.Println(ToFixed(b, 2))
fmt.Println(ToFixed(c, 2))
fmt.Println(ToFixed(d, 2))
}
//use in rateConversion
func ToFixed(num float64, precision uint) float64 {
output := math.Pow(10, float64(precision))
return float64(round(num*output)) / output
}
func round(num float64) int {
return int(num + math.Copysign(0.5, num))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment