william007
william007

Reputation: 18525

Cannot convert expression of type 'float64' to type 'int64'

package main

import (
    "fmt"
)

func main(){

    //float to int
    fmt.Println(int64(1.9))

}

I got syntax error "Cannot convert expression of type 'float64' to type 'int64'", how to rectify it?

Upvotes: 7

Views: 5563

Answers (2)

Marc
Marc

Reputation: 21035

Type conversions have special rules for constants:

A constant value x can be converted to type T if x is representable by a value of T.

And even gives the following example:

int(1.2)                 // illegal: 1.2 cannot be represented as an int

If you really insist on truncating your float into an int, use a variable as an intermediary turning it into a non-constant conversion. Go will happily do the conversion and drop the fractional part, as mentioned further down in the spec:

When converting a floating-point number to an integer, the fraction is discarded (truncation towards zero).

So you can use the following:

package main

import (
    "fmt"
)

func main() {

    //float to int
    f := 1.9
    fmt.Println(int64(f))
}

Which outputs 1 as expected.


Or use one of the functions in the math package if you want finer control over rounding vs truncation.

Upvotes: 11

EldadT
EldadT

Reputation: 932

Jut use the math package:

int64(math.Floor(1.9))

playground

Upvotes: 0

Related Questions