本文介绍了在 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"
}
这篇关于在 Go 中将 float64 转换为 int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!