Home » Golang – Convert String to Integer

Golang – Convert String to Integer

Use the Atoi() function of the strconv package in golang to convert the string to an integer value. Atoi() function takes a string as an input parameter and returns an integer value and the error if any.

In this article, we will discuss how to convert a string to an integer in golang using the Atoi() function.

Convert String to Int in golang

To convert String to int in go language, use the strconv package available in golang. You will need to import the strconv package to use Atoi() function.

To convert String to int in golang using Atoi() function:

  1. Import the strconv golang package
  2. Use strconv.Atoi() method to convert a String to an integer.
  3. Pass the string value to Atoi() method
  4. Atoi() method returns integer and error (if any)
  5. use the fmt.Println method to print converted integer value and error (if any)
package main

import (
	"fmt"
	"strconv"
)

func main() {
	s_value := "15"
        // use strconv.Atoi() to convert string to int
	i_value, err := strconv.Atoi(s_value)
	fmt.Println(i_value, err)   
}

The output of the above golang program is:

15 <nil>

Note here that, strconv.Atoi() method converts the string value having a valid number to an integer value.

Parse String to Int using Atoi()

strconv.Atoi() method accepts the string parameter and returns an integer and error (if any). If the string parameter is not a valid number, then Atoi() method will return an error while parsing the string to an integer.

Convert String to int using Atoi() method:

  1. Import the strconv golang package
  2. Use strconv.Atoi() method to convert String to an integer.
  3. Pass the string value to Atoi() method
  4. Atoi() method returns integer and error (if any)
  5. use the fmt.Println method to print converted integer value and error (if any)
package main

import (
	"fmt"
	"strconv"
)

func main() {
	s_value := "StringTest15"
        // use strconv.Atoi() to convert string to int
	i_value, err := strconv.Atoi(s_value)
	fmt.Println(i_value, err)   
}

In the above golang program, we have passed a string that doesn’t contain a valid number to Atoi() method.

Atoi() method failed to parse string value to integer and returns an error “strconv.Atoi: parsing “Stringtest15” : invalid syntax.

The output of the above golang program is:

0 strconv.Atoi: parsing "StringTest15": invalid syntax

Conclusion

I hope the above article on how to convert String to integer in golang is helpful to you.

Use the strconv package in golang that provides Atoi() method to convert the String to an integer. If the string parameter passed to Atoi() method is not a valid number, it will return an error while parsing.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Recommended Content

Golang Float64 Max and Min Value

Golang Max and Min Value of Integer

Golang Round Float64 to Integer

Golang Convert Int to String

Leave a Comment