7
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?

8
  • 1
    Which version of Go are you using? The build error is constant 1.9 truncated to integer Commented Sep 29, 2020 at 14:28
  • 1
    What is the question? Commented Sep 29, 2020 at 14:30
  • @Marc The version "go version go1.15.2 linux/amd64" Commented Sep 29, 2020 at 14:31
  • @kostix What do you mean? Commented Sep 29, 2020 at 14:31
  • 1
    I mean, the behaviour you're facing is documented as «The values of typed constants must always be accurately representable by values of the constant type. The following constant expressions are illegal: <…> int(3.14) // 3.14 cannot be represented as an int». May be use fmt.Println(math.Trunc(1.9))? Commented Sep 29, 2020 at 14:36

2 Answers 2

11

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Jut use the math package:

int64(math.Floor(1.9))

playground

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.