如何在Golang中将字符串转换为整数 [英] How can I convert string to integer in golang
问题描述
我想在golang中将字符串转换为整数。但是我不知道字符串的格式。例如, 10
-> 10
, 65.0
-> 65
, xx
-> 0
, 11xx-> 11, xx11-> 0
I want to convert string to integer in golang. But I don't know the format of string. For example, "10"
-> 10
, "65.0"
-> 65
, "xx"
-> 0
, "11xx" -> 11, "xx11"->0
我做了一些搜索,找到了 strconv.ParseInt()
。但是它不能处理 65.0
。因此,我必须检查字符串的格式。
I do some searching and find strconv.ParseInt()
. But it can not handle "65.0"
. So I have to check string's format.
有更好的方法吗?
推荐答案
我相信您要查找的函数是
I believe function you are looking for is
strconv.ParseFloat()
请参阅示例此处
但是此函数的返回类型为float64。
But return type of this function is float64.
如果不需要小数作为字符串后面的函数传递的数字的一部分将完成这项工作:
If you don't need fractional part of the number passed as the string following function would do the job:
func StrToInt(str string) (int, error) {
nonFractionalPart := strings.Split(str, ".")
return strconv.Atoi(nonFractionalPart[0])
}
这篇关于如何在Golang中将字符串转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!