New to GO- how it handles float precision 0.4 + 0.2 is 0.6

Go’s float32 and float64 types follow IEEE 754, just like many other languages. This means that it will be subject to the same limitations.

package main

import "fmt"

func main() {
	fmt.Printf("%T %T\n", 0.2, 0.2+0.4) // float64 float64

	fmt.Println(0.2 + 0.4)                   // 0.6
	fmt.Println(float32(0.2) + float32(0.4)) // 0.6
	fmt.Println(float64(0.2) + float64(0.4)) // 0.6000000000000001
}

playground

Regarding fmt.Println(0.2 + 0.4), the expression contains only literal constants and as such will be evaluated at compile time rather than runtime.

2 Likes