DEV Community

Shubham Chadokar
Shubham Chadokar

Posted on

Convert String to Int and Int to String in Golang

Golang standard library has provided 2 functions Atoi and Itoa to convert string to int and int to string respectively.

Originally published on schadokar.dev

These 2 functions placed inside the strconv package.

Package strconv implements conversions to and from string representations of basic data types.

String to Int

The strconv.Atoi function takes a string and returns an int and an error.

func Atoi(s string) (int, error)
Enter fullscreen mode Exit fullscreen mode

It will return type int and type int is system dependent. It is 32 bits on the 32-bit system and 64 bits on the 64-bit system.

💡 Use the term ASCII to Int to remember the func name.

package main

import (
    "fmt"
    "strconv"
)

func main() {

    str := "1234"

    i, err := strconv.Atoi(str)

    if err != nil {
        fmt.Println(err)
    }

    fmt.Printf("Type: %T, Value: %v\n", i, i)

    // convert int to int64
    i64 := int64(i)
    fmt.Printf("Type: %T, Value: %v", i64, i64)
}
Enter fullscreen mode Exit fullscreen mode

Output

Type: int, Value: 1234
Type: int64, Value: 1234
Enter fullscreen mode Exit fullscreen mode

Int to String

The strconv.Itoa takes int as an argument and returns the string.

func Itoa(i int) string
Enter fullscreen mode Exit fullscreen mode

Example:

package main

import (
    "fmt"
    "strconv"
)

func main() {
    num := 322020

    str := strconv.Itoa(num)

    fmt.Printf("Type: %T, Value: %v", str, str)
}
Enter fullscreen mode Exit fullscreen mode

Output

Type: string, Value: 322020
Enter fullscreen mode Exit fullscreen mode

Top comments (0)