Convert String to Integer

To convert a String to an Integer in Go programming, use Atoi() function of strconv package. Pass the string value to Atoi() function as argument.

In this tutorial, we will learn how to parse or convert a string to integer.

Sample Code Snippet

The sample code snippet to use Atoi() function is given in the following.

</>
Copy
// import statement
import "strconv"

// convert string to integer
number, error = strconv.Atoi("14")

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

Atoi means A(Alphabets or String) to i(integer).

Examples

Positive Scenario

In the following program, we take a string str that has only a numeric value and convert this string value to integer value using strconv.Atoi() function.

example.go

</>
Copy
package main

import "fmt"
import "strconv"

func main() {
	var str = "14"
	// convert string to integer
	number, error := strconv.Atoi(str)
	fmt.Println("error:", error)
	fmt.Println("number:", number)
}

Output

error: <nil>
number: 14

Now, let us go through a negative scenario, where the string, we would like to convert to integer, is not a valid number.

Negative Scenario

In the following program, we will take a string that has also non-numeric characters. We will try converting it to a number. We should get an error.

example.go

</>
Copy
package main

import "fmt"
import "strconv"

func main() {
	var str = "14sup."
	// convert string to integer
	number, error := strconv.Atoi(str)
	fmt.Println("error:", error)
	fmt.Println("number:", number)
}

Output

error: strconv.Atoi: parsing "14sup.": invalid syntax
number: 0

We received a “invalid syntax” error while trying to parse a string that contains non-numeric characters.

Conclusion

In this Golang Tutorial, we learned how to convert a String to Integer in Go language, with example programs.