0

How does the float arithmetic work in Go

Playground link

package main

import "fmt"

func main() {
    j := 1.021
    fmt.Println(j)
    k := j*1000
    fmt.Println(k)
    l := int(k)
    fmt.Println(l)
}

Output:
1.021
1020.9999999999999
1020

I was expecting 1021 to be printed, but I got 1020

Sundar
  • 1,691
  • 1
  • 14
  • 20
  • 1
    Maybe your surprise comes from ignoring that 1.021 is not exactly the fraction 1021/1000, but the nearest possible float to this fraction... Please read the literature recommended with the floating-point tag. – aka.nice Nov 10 '15 at 22:50
  • Thanks. That clarifies it. Interestingly, I did not understand why I got downvotes for the question. I indeed searched around and was not able to find a clear reason. Somehow I thought this was Go specific, while it seems very generic. – Sundar Nov 11 '15 at 10:27
  • @ThomasPadron-McCarthy yes, it is. Thanks. Interestingly that post got 811 upvotes, while mine -3. – Sundar Nov 12 '15 at 10:29
  • More explanation here @ http://0.30000000000000004.com – Sundar Nov 13 '15 at 12:19

1 Answers1

5

Go, like everyone else, uses IEEE-754 binary floating-point arithmetic. Floating-point arithmetic is inexact for some decimal values.

References:

Floating point

IEEE floating point

peterSO
  • 158,998
  • 31
  • 281
  • 276