Convert string to int/int64

yourbasic.org/golang

String to int

Use strconv.Atoi to convert/parse a string to an int.

str := "123"
if n, err := strconv.Atoi(str); err == nil {
    fmt.Println(n+1)
} else {
    fmt.Println(str, "is not an integer.")
}
// Output: 124

String to int64

Use strconv.ParseInt to parse a decimal string (base 10) and check if it fits into a 64-bit signed integer.

str := "123"
n, err := strconv.ParseInt(str, 10, 64)
if err == nil {
    fmt.Printf("%d of type %T", n, n)
}
// Output: 123 of type int64

The two numeric arguments represent a base (0, 2 to 36) and a bit size (0 to 64).

If the first argument is 0, the base is implied by the string’s prefix: base 16 for "0x", base 8 for "0", and base 10 otherwise.

The second argument specifies the integer type that the result must fit into. Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64.

Further reading

String functions cheat sheet

Share this page: