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
I do some searching and find strconv.ParseInt(). But it can not handle "65.0". So I have to check string's format.
Is there a better way?
解决方案
I believe function you are looking for is
strconv.ParseFloat()
see example here
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])
}
本文探讨了在Go语言中如何将不同格式的字符串转换为整数,包括处理包含小数点的字符串。建议使用strconv.ParseFloat()函数处理包含小数的字符串,并提供了一个自定义函数StrToInt()来移除小数部分并进行转换。该函数通过分割字符串去除小数点后转换为整数。
1945

被折叠的 条评论
为什么被折叠?



