Skip to content

Instantly share code, notes, and snippets.

@drKnoxy
Created April 21, 2016 18:27
Show Gist options
  • Save drKnoxy/84d9c80fb0656239cef7825182c0621e to your computer and use it in GitHub Desktop.
Save drKnoxy/84d9c80fb0656239cef7825182c0621e to your computer and use it in GitHub Desktop.
Truncating vs. Rounding in go
// http://play.golang.org/p/KNhgeuU5sT
package main
import (
"fmt"
"math"
)
// truncate a float to two levels of precision
func Truncate(some float64) float64 {
return float64(int(some * 100)) / 100
}
func Round(val float64, roundOn float64, places int) float64 {
pow := math.Pow(10, float64(places))
digit := pow * val
_, div := math.Modf(digit)
var round float64
if val > 0 {
if div >= roundOn {
round = math.Ceil(digit)
} else {
round = math.Floor(digit)
}
} else {
if div >= roundOn {
round = math.Floor(digit)
} else {
round = math.Ceil(digit)
}
}
return round / pow
}
func RoundPrice(price float64) float64 {
return Round(price, 0.5, 2)
}
func main() {
floatTests := []float64{
10 / 3.0,
-10 / 3.0,
-38.288888,
}
fmt.Println("original", "truncated", "rounded")
for _, k := range floatTests {
t := Truncate(k)
r := RoundPrice(k)
fmt.Println(k, t, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment