golang中如何将字符串转换为整数 [英] How can I convert string to integer in golang

查看:51
本文介绍了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.

有没有更好的办法?

推荐答案

相信你要找的功能是

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屋!

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