在Go中将float64转换为int [英] Convert a float64 to an int in Go

查看:10251
本文介绍了在Go中将float64转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  package main 
importfmt
func main(){
var x float64 = 5.7
var y int = int(x)
fmt。 Println(y)//输出5
}


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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆