How to Use strconv.atoi() Function in Go

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

Diagram

Diagram of strconv.atoi() Function in Golang

Syntax

func Atoi(s string) (int, error)

Parameters

string: 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.

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

Example 1: How to Use strconv.Atoi() Function

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

Example 2: Simple Go Program

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

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 a strconv.Atoi: parsing “ff”: invalid syntax error.

Similar posts

  1. strconv.ParseInt()
  2. strconv.FormatInt()