DEV Community

Shubham Chadokar
Shubham Chadokar

Posted on

2 3

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay