doubo3384 2015-07-18 04:08
浏览 222

如何在Golang中将字符串转换为整数

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?

  • 写回答

6条回答 默认 最新

  • dongxiangqian1855 2015-07-18 08:49
    关注

    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])
    }
    
    评论

报告相同问题?