How to Convert string to integer type in Golang?
Last Updated :
14 Sep, 2021
Improve
Strings in Golang is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding. In Go language, both signed and unsigned integers are available in four different sizes. In order to convert string to integer type in Golang, you can use the following methods.
1. Atoi() Function: The Atoi stands for ASCII to integer and returns the result of ParseInt(s, 10, 0) converted to type int.
Syntax:
func Atoi(s string) (int, error)
Example:
Go
// Go program to illustrate how to // Convert string to the integer type package main import ( "fmt" "strconv" ) func main() { str1 := "123" // using ParseInt method int1, err := strconv.ParseInt(str1, 6 , 12 ) fmt.Println(int1) // If the input string contains the integer // greater than base, get the zero value in return str2 := "123" int2, err := strconv.ParseInt(str2, 2 , 32 ) fmt.Println(int2, err) } |
Output:
123 0 strconv.Atoi: parsing "12.3": invalid syntax
2. ParseInt() Function: The ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
Syntax:
func ParseInt(s string, base int, bitSize int) (i int64, err error)
Example:
Go
// Go program to illustrate how to // Convert string to the integer type package main import ( "fmt" "strconv" ) func main() { str1 := "123" // using ParseInt method int1, err := strconv.ParseInt(str1, 6 , 12 ) fmt.Println(int1) // If the input string contains the integer // greater than base, get the zero value in return str2 := "123" int2, err := strconv.ParseInt(str2, 2 , 32 ) fmt.Println(int2, err) } |
Output:
51 0 strconv.ParseInt: parsing "123": invalid syntax