Number Conversion

Hey there…

Why below code works;

    x := 111.120

And below one not;



This is due to how Go handles constants. There is a good blog post about that here:

Your function call


is essentially equivalent to

const c0 = 111.12   // floating point constant
const c1 = int(c0)  // attempted conversion to integer constant

But you can’t convert a floating point constant to an integer constant. You can however convert a float64 variable to int, which is what you’re doing in the first example.

Go constants are unusual in that they live in a hypothetical infinite precision mathematical space, as opposed to the practical limited-by-a-certain-number-of-bits world that variables live in. For example:

const c0 = 112.12e3 // actually an integer constant
const c1 = int(c0)  // fine
fmt.Println(c1)     // "112120"

but also

const c0 = 112.12e100 // a larger integer constant
const c1 = int(c0)    // constant 11212000...000 overflows int


const c0 = 112.12e100
const c1 = c0 / 1e98   // integer constant, value 11212
const c2 = c0 / 1e99   // floating point constant, value 1121.2
fmt.Println(c1, c2)    // "11212 1121.2"
1 Like

Of course It makes Sense, I just need tô truncate It to 111, int() method did it. Tnx.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.