Skip to content

Instantly share code, notes, and snippets.

@wlbr
Last active January 12, 2021 09:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wlbr/9e1035d09d9fc1c1086eef43714857f7 to your computer and use it in GitHub Desktop.
Save wlbr/9e1035d09d9fc1c1086eef43714857f7 to your computer and use it in GitHub Desktop.
Fun with floating point precision in Go
package main
import (
"fmt"
"math/big"
)
func main() {
var a, b, c float32
// The bad way
a = 0.1
b = 0.2
c = a * b
fmt.Println(c)
fmt.Println(a * b)
// The "with Go don't go that way" way
d := 0.1 * 0.2
fmt.Println(d)
fmt.Println(0.1 * 0.2)
// The good way
m := big.NewFloat(0.1)
n := big.NewFloat(0.2)
var o big.Float
//take care that o is of a different type than m and n (big.Float vs *big.Float)
o.Mul(m, n)
fmt.Println(o.String())
/* ==>
0.020000001
0.020000001
0.02
0.02
0.02
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment