HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

Convert a float64 to an int in Go

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
convertfloat64int

Problem

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?

Solution

package main
import "fmt"
func main() {
  var x float64 = 5.7
  var y int = int(x)
  fmt.Println(y)  // outputs "5"
}

Code Snippets

package main
import "fmt"
func main() {
  var x float64 = 5.7
  var y int = int(x)
  fmt.Println(y)  // outputs "5"
}

Context

Stack Overflow Q#8022389, score: 338

Revisions (0)

No revisions yet.