简体   繁体   中英

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?

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.

Jut use the math package:

int64(math.Floor(1.9))

playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM