Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert string to integer in 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?

like image 741
shenli3514 Avatar asked Jul 18 '15 04:07

shenli3514


People also ask

What is Atoi in Golang?

Atoi() The Atoi() function is an inbuilt function of the strconv package which is used to convert (interpret) a given string s in the given base (10) and bit size (0) and returns the corresponding integer value. The Atoi() function is equivalent to ParseInt(s, 10, 0), converted to type int.

How do I convert type in Golang?

Type conversion happens when we assign the value of one data type to another. Statically typed languages like C/C++, Java, provide the support for Implicit Type Conversion but Golang is different, as it doesn't support the Automatic Type Conversion or Implicit Type Conversion even if the data types are compatible.

What is int64 in Golang?

int64 is a version of int that only stores signed numeric values composed of up to 64 bits. So, for example, if you try to store a string value in it, or an integer beyond what can be made using 64 bits, the program would return an error or result in an integer overflow.


2 Answers

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])
}
like image 171
Mayank Patel Avatar answered Oct 02 '22 02:10

Mayank Patel


You can use these three functions to convert a string value to an integer or a float.

Note: the strconv builtin package must be imported to execute these functions.

  1. func Atoi(s string) (int, error)
  2. func ParseInt(s string, base int, bitSize int) (i int64, err error)
  3. func ParseFloat(s string, bitSize int) (float64, error)
package main

import (
    "fmt"
    "strconv"
)

func main() {
    i, _ := strconv.Atoi("-42")
    fmt.Println(i)

    j,_ := strconv.ParseInt("-42", 10, 8)
    fmt.Println(j)

    k,_ := strconv.ParseFloat("-42.8", 8)
    fmt.Println(k)
}
like image 8
0example.com Avatar answered Oct 01 '22 02:10

0example.com