golang

Golang convert string to int – example


In Golang, you can convert string to int type using the following functions.

  1. strconv.ParseInt(s, base, bitSize)
  2. strconv.Atoi(s)

Let’s checkout the example of above functions:

1. Golang convert string to int using strconv.ParseInt(s, base, bitSize)

package main

import (
	"fmt"
	"strconv"
)

func main() {
	str := "1111"

	n, err := strconv.ParseInt(str, 2, 32)

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

The strconv.ParseInt(s, base, bitSize) converts the given string to an integer in the given base (0, 2 to 36) and bit size (0 to 64). The output of the above code will be 15 .

2 Golang convert string to int using strconv.Atoi(s) method

package main

import (  
    "fmt"
    "strconv"
)

func main() {  
    str := "3"

    n, _ := strconv.Atoi(str)
    fmt.Println(n)
}

we use strconv.Atoi(s) to convert a string s to a 32 bit integer. The output of the above code will be 3 .


Share on social media

//