Convert string to int in Golang ?

golang convert string to int

This golang tutorials help to convert string to integer in golang. We will discuss the number of ways to convert a string into an integer. Both signed and unsigned integers are accessible in four sizes in the Go language.

We may occasionally receive a number in string format and need to perform a mathematical operation on it. To conduct any mathematical action, we must explicitly convert this string type to an integer type.

Convert string into Int

You can use one of the following ways to convert a string to an int:

  • strconv.Atoi: Atoi returns the result of ParseInt(s, 10, 0) converted to type int.
  • strconv.ParseInt: ParseInt interprets a string s in the given base (2 to 36) and returns the corresponding value i.

Convert string to int Using Atoi

The strconv package Itoa() function can be used to convert the string into an integer value.

Syntax

func Atoi(s string) (int, error)

strconv.Atoi() takes a string as an argument and returns an integer. The function also returns an error. error object will be null if there is no error.

Let’s see the below example:

package main

import (
  "fmt"
  "strconv"
)

func main() {
  i := "12"
  if a, err := strconv.Atoi(i); err == nil {
        fmt.Printf("%T, %v\n", a, a)
  }
}

Output:

int, 12

Convert string to int Using ParseInt

The ParseInt() a function can be used to convert the string into an integer value. This function accepts a string parameter, converts it into a corresponding int type based on a base parameter.

Syntax

func ParseInt(s string, base int, bitSize int) (i int64, err error)

The parameters are :

s: The source string and may begin with a leading sign: “+” or “-“.
base : The base (0, 2 to 36)
bitSize: This argument specifies the integer type (0 to 64). The bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64. size

Let’s see the below example:

package main

import (
  "fmt"
  "strconv"
)

func main() {
  i := "12"
  if a, err := strconv.ParseInt(i, 10, 64); err == nil {
        fmt.Printf("%T, %v\n", a, a)
  }
}

Output:

int64, 12