What is the strconv.atoi() Function in Golang

Golang strconv.Atoi() is equivalent to ParseInt() function “used to convert string type into int type.” It takes an integer as an argument and returns the string representation of the input value.

Syntax

func Atoi(s string) (int, error)

Arguments

The Atoi() method takes a string as an argument.

Return value

It returns an integer or an error if the value is incompatible with converting it into an integer.

Example 1

To use the Atoi() function in Golang, you must import the strconv package into your program.

In addition, the fmt package is valid when you need to execute I/O operations like printing on the console.

package main

import (
 "fmt"
 "strconv"
)

func main() {
   dataString := "19"
   fmt.Printf("%v \n", dataString)
   fmt.Printf("%T \n", dataString)
   fmt.Println("After using Atoi() Function")
   if s, err := strconv.Atoi(dataString); err == nil {
   fmt.Printf("%v \n", s)
   fmt.Printf("%T \n", s)
 }
}

Output

19
string

After using Atoi() Function

19
int

In this example, we imported two packages.

  1. fmt
  2. strconv

Inside the main() function, we declare a variable with a string value and print its value and data type.

Using the if statement, we convert a string to an integer using strconv.Atoi() function.

The Atoi() function is equivalent to ParseInt() function, which is also helpful to convert to type int.

Example 2

package main

import (
 "fmt"
 "strconv"
)

func main() {
   fmt.Println(strconv.Atoi("19"))
   fmt.Println(strconv.Atoi("-19"))
   fmt.Println(strconv.Atoi("212121"))
   fmt.Println(strconv.Atoi("-2119"))
   
   fmt.Println(strconv.Atoi("ff"))
   fmt.Println(strconv.Atoi("123abc"))
}

Output

19 <nil>
-19 <nil>
212121 <nil>
-2119 <nil>
0 strconv.Atoi: parsing "ff": invalid syntax
0 strconv.Atoi: parsing "123abc": invalid syntax

We took every possible string type in this example and converted it into an integer.

The strconv.Atoi() function also returns an error. The error object will be nil if there is no error.

In this example, if there is no error, nil is returned. Otherwise, an error is returned. For example, while parsing, if it finds a string that can not be converted into an integer, it returns an invalid syntax error.

The Atoi() function is a convenient method for base-10 int parsing.

Related Posts

Golang Itoa()

Leave a Comment