Convert a float64 to an int in Go

go
Chris Bunch picture Chris Bunch · Nov 5, 2011 · Viewed 174.1k times · Source

How does one convert a float64 to an int in Go? I know the strconv package can be used to convert anything to or from a string, but not between data types where one isn't a string. I know I can use fmt.Sprintf to convert anything to a string, and then strconv it to the data type I need, but this extra conversion seems a bit clumsy - is there a better way to do this?

Answer

David Grayson picture David Grayson · Nov 5, 2011
package main
import "fmt"
func main() {
  var x float64 = 5.7
  var y int = int(x)
  fmt.Println(y)  // outputs "5"
}