Golang Itoa: How to use strconv.Itoa() Function

Go provides built-in support to execute conversions to and from string expressions of basic data types using the strconv Package. The most familiar numeric conversions are converting string to int using Atoi() and converting int to string using Itoa() function in Go. In this article, we will learn what is strconv.Itoa() function and how to use it.

Golang Itoa

The Itoa() is a function of the strconv Package that returns the string representation of the input value when the base is 10. The strconv.Itoa() function is to similar to FormatInt(int64(i), 10).

Syntax

func Itoa(i int) string

Arguments

The function Itoa() takes an input i of type integer.

Return Value

The strconv.Itoa() function returns a string that represents i.

Example

package main

import (
 "fmt"
 "strconv"
)

func main() {
 str1 := strconv.Itoa(19)
 fmt.Printf("%T, %v\n", str1, str1)

 str2 := strconv.Itoa(21)
 fmt.Printf("%T, %v\n", str2, str2)
}

Output

string, 19
string, 21

In this example, we imported two packages.

  1. fmt
  2. strconv

The fmt package provides I/O functions like Printf() that prints the output on the console.

To get the data type of a variable in Go, use the %T inside the Printf() function, which prints the data type of a variable.

The strconv.Itoa() function converts an integer to a string, and we printed its data type, which is a string.

Using negative integer as argument

Let’s take a negative integer as an input to the strconv.Itoa() function.

package main

import (
 "fmt"
 "strconv"
)

func main() {
 int1 := -19
 fmt.Printf("Output: %d \n", int1)
 fmt.Printf("Data Type: %T \n", int1)
 fmt.Println("After conversion:")
 str1 := strconv.Itoa(int1)
 fmt.Printf("Output: %v \n", str1)
 fmt.Printf("Output: %T \n", str1)
}

Output

Output: -19
Data Type: int
After conversion:
Output: -19
Output: string

We assigned a negative integer value to a variable and printed its value and data type in this example.

We are then using strconv.Itoa() method, we converted from integer to string and printed its value and data type, which is a string.

That’s it for Golang Itoa() method.

Leave a Comment