在 Go 中将 float64 转换为 int

在 Go 中将 float64 转换为 int

问题描述:

在 Go 中如何将 float64 转换为 int?我知道 strconv 包可用于将任何内容转换为字符串或从字符串转换任何内容,但不能在不是字符串的数据类型之间进行转换.我知道我可以使用 fmt.Sprintf 将任何内容转换为字符串,然后 strconv 将其转换为我需要的数据类型,但是这种额外的转换似乎有点笨拙 - 是有更好的方法吗?

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?

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