Put floating point number

I am trying to get 2.4 / 0.8 == 3 in Go

w:=float64(2.4)
fmt.Println(math.Floor(w/0.8),math.Floor(2.4/0.8) )

He gives me "2 3".

The question is why math.Floor(w/0.8)it won’t give me 3. Is the precision limit of a floating point number?

+5
source share
3 answers

The result of the program is correct. The representation of many real numbers in the IEEE format is inaccurate. The first number is actually (in limited 64-bit versions) less than 3, so the floor returns "2" correctly. The second of them is computed at compile time with greater accuracy.

Recommended reading .

+9
source

, . float64 , 2.4 . , , float64, 3. , , 2.9999999999999996, 2.

+7

Although this does not answer the question (why), I found this page in search of a round function, so in case someone finds it useful, this is my own solution:

   func Round(val float64) (float64) {
        if float64(int(val)) < val {
            return float64(int(val) + 1)
        }
        return val
    }
0
source

All Articles