# How to Convert Golang Int to String? Read it later

In the world of Golang, converting an int to a string, a string to int/int64, and int to int64 is a common and important task. We’ll focus on the `strconv` package’s Itoa, Atoi, int64, and FormatInt functions, as well as the fmt package’s Sprintf function. By the end, you’ll have the knowledge to perform this conversion seamlessly. Let’s get started on this exciting journey!

## Golang Convert Between int and int64

Understanding how to convert between int and int64 is essential before delving into the conversion of int/int64 to string and vice versa. Let’s explore these conversions to establish a solid foundation.

#### Convert int to int64

To convert an int to int64, we can utilize the `int64()` function.

Consider the following code example:

``````var a int = 17
var n int64 = int64(a)
fmt.Println(reflect.TypeOf(n))``````

In this example, we have an integer variable `a` with a value of 17. By applying the int64() function to `a`, we convert it to the corresponding int64 representation. The resulting value is stored in the variable `n`.

Finally, we print the type of `n` using the reflect package’s `TypeOf()` function to confirm the successful conversion.

#### Convert int64 to int in Go

Similarly, converting from int64 to int can be achieved using the `int()` function. Let’s take a look at the following code example:

``````var a int64 = 17
var n int = int(a)
fmt.Println(reflect.TypeOf(n))``````

In this code example, we have an int64 variable `a` with a value of 17. By applying the int() function to `a`, we convert it to the corresponding int representation. The resulting value is stored in the variable `n`. Finally, we print the type of `n` using the reflect package’s TypeOf() function.

Also, read how to convert Golang Interface to String.

## Golang Convert Between String and int/int64

Let’s explore how we can convert a string to an int or int64 in Golang. There are a few methods we can use, and we’ll walk you through each one step by step.

#### 1. Using strconv.Atoi Function

The `strconv.Atoi` function allows us to convert a string to an int in Golang. Here’s an example that demonstrates its usage:

``````s := "17"
n, err := strconv.Atoi(s)
fmt.Println("Error: ", err)
fmt.Println("Number: ", n)
fmt.Println("Type: ", reflect.TypeOf(n))
``````

In this code snippet, we start with a string variable `s` containing the value “17”. By calling `strconv.Atoi(s)`, we convert the string to an int. The converted value is stored in the variable `n`, and any error that may occur during the conversion is captured in the `err` variable.

Finally, we print the error, the converted number, and its type to the console.

Output:

``````Error:  <nil>
Number:  17
Type:  int``````

#### 2. Using strconv.ParseInt

Another method to convert a string to an int or int64 is by using the `strconv.ParseInt` function. This function allows us to parse a decimal string with a specified base and check if it fits into an int64.

Here’s an example illustrating its usage:

``````s := "17"
n, err := strconv.ParseInt(s, 10, 64)
fmt.Println("Error: ", err)
fmt.Println("Number: ", n)
fmt.Println("Type: ", reflect.TypeOf(n))``````

In the above example, we provide the string value “17” to the `strconv.ParseInt()` function. The second argument, `10`, represents the decimal base. The third argument, `64`, indicates that the result should fit into an int64.

The converted value is stored in the variable `n`, and any error encountered is captured in the `err` variable. Finally, we print the error, the converted number, and its type to the console.

The strconv.ParseInt function accepts three arguments:

1. Numerical string value: The string can include a leading sign, either “+” or “-“.
2. Base: The base argument specifies the numerical base of the string. If the base is set to 0, the function infers the base from the string’s prefix. For example, “0b” corresponds to base 2, “0” or “0o” corresponds to base 8, “0x” corresponds to base 16, and any other value corresponds to base 10.
3. Int Bit Size: The bitSize argument specifies the integer type that the result must fit into. Valid options include 0, 8, 16, 32, and 64, corresponding to int, int8, int16, int32, and int64, respectively. If the bitSize is outside this range, an error will be returned.

## Golang Convert int/int64 to String

Before we dive into the methods for converting an int or int64 to a string in Golang, let’s take a moment to understand the challenges we may encounter during a standard conversion.

### Understanding The Problem

You might be thinking, “What is there to understand about converting an int/int64 to a string? Just tell me how to do it in Golang”. Well, hold on for a moment. Let’s dig deeper into the problem and unravel some surprising insights.

When we consider converting an int/int64 to a string, the first method that often comes to mind is using the `string()` function. It seems like an easy approach, right? Let’s give it a try and convert an int/int64 to a string using the `string()` function:

``````func main() {
var i int = 68
s := string(i)
fmt.Println(s)
}``````

Output:

``D``

Wait a minute! Why are we getting ‘D’ as the output when we try to convert 68 to a string? Don’t worry; there’s nothing wrong with the code. Let me explain what’s happening here.

The `string()` function, in its current form, converts an integer to the corresponding ASCII character. Yes, you heard that right! In our example, the integer 68 is being converted to its ASCII equivalent, which happens to be ‘D’. So, rather than getting the string representation of the number 68, we end up with the character ‘D’ instead.

📝 Note: The `string()` function only performs ASCII-to-string conversions and does not handle UTF-8 encoded strings.

💡Curious to know the differences between ASCII and UTF-8 and the various types of conversions supported by Golang’s UTF-8 encoding, be sure to check out our insightful blog on Golang UTF-8 Encoding.

#### The Saviour

So, can we convert an int/int64 to a string in Golang? Don’t worry, my dear friend! Golang comes to our rescue with the `strconv` and `fmt` packages, offering functions capable of converting an int to a string.

In Golang, the `strconv` package provides `strconv.Itoa()`, which effortlessly converts an int to its string representation. The `fmt` package introduces `fmt.Sprintf()`, allowing us to format the resulting string. Additionally, the `strconv.FormatInt()` function offers more control by specifying the base of the string representation.

Now, let’s explore these functions and how they work in detail.

### Golang int/int64 to string Using Itoa

Let’s embark on our journey of converting an integer to a string in Golang with the widely known Itoa function. Itoa, which stands for “integer to ASCII“, is a powerful function that accomplishes the task efficiently.

It is worth mentioning that Itoa is equivalent to using `FormatInt(int64(i), 10)`. Don’t worry if you’re not familiar with FormatInt yet, we’ll cover it later in this blog. For now, let’s focus on Itoa and its practical implementation.

Syntax of `strconv.Itoa()` function:

``func Itoa(i int) string``

Enough theory! Let’s get straight to an example to see it in action:

``````package main

import (
"fmt"
"reflect"
"strconv"
)

func main() {
i := 68
fmt.Println("Before conversion:", i, reflect.TypeOf(i))
s := strconv.Itoa(i)
fmt.Println("After conversion:", s, reflect.TypeOf(s))
}``````

In this code snippet, we have an integer variable `i` with the value 68. Before the conversion, we print the original value of `i` along with its type using `reflect.TypeOf()`. Next, we apply the Itoa function by invoking `strconv.Itoa(i)` and store the resulting string in the variable `s`. Finally, we print the converted string `s` and its type.

##### Output

Let’s take a look at the output of this example:

``````Before conversion: 68 int
After conversion: 68 string``````

As you can see, the output confirms the successful conversion of the integer to a string. Earlier, when we attempted to convert the integer to a string using the `string()` function, we obtained an undesired result, such as ‘D’. However, by utilizing Itoa, we achieved the desired outcome.

#### Problem with Itoa

When using the `strconv.Itoa()` function for converting an int/int64 to a string in Golang, there is a particular issue you might encounter, and that relates to error handling. As you may recall, from the function’s syntax, it solely returns a string without an accompanying error. Consequently, if any problem arises during the conversion process, you won’t receive an error indication. Let’s examine this concern through an illustrative example:

Consider the following code snippet:

``````str := "hello"
num, err := strconv.Atoi(str)
if err != nil {
fmt.Println("Error:", err)
}
a := strconv.Itoa(num)
fmt.Println("Converted Int to String:", a)
fmt.Println("Type:", reflect.TypeOf(a))``````

Upon execution, you’ll observe the following output:

``````Error: strconv.Atoi: parsing "hello": invalid syntax
Converted Int to String: 0
Type: string``````

In this example, we attempted to convert the string “hello” to an integer using `strconv.Atoi()`. As expected, this operation encountered an error due to the invalid syntax. However, when we subsequently applied `strconv.Itoa()` to convert the resulting integer back to a string, we encountered a different outcome. Instead of receiving an error message, the function returned “0” as the converted string. This behavior can be misleading if you are not aware of the initial error during the conversion.

#### Solution

To mitigate this problem, it is essential to implement appropriate error-handling techniques when working with `strconv.Atoi()` and `strconv.Itoa()`. Always remember to check the error value returned by `strconv.Atoi()` to ensure the conversion was successful before proceeding with any further operations.

Example:

``````func main() {
str := "hello"
num, err := strconv.Atoi(str)
if err != nil {
fmt.Println("Error:", err)
}

strConverted := strconv.Itoa(num)
if strConverted == "0" {
fmt.Println("Conversion failed")
return
}
fmt.Println("String:", strConverted)
}``````

### Go int/int64 to String Using FormatInt

Another useful method for converting an integer to a string in Golang is by utilizing the `strconv.FormatInt()` function. This function allows you to specify the base for the resulting string, providing flexibility in how the conversion is performed.

The syntax for using FormatInt is as follows:

``func FormatInt(i int64, base int) string``

Let’s break down the parameters and understand their significance:

• `i`: This parameter represents the integer value that we want to convert to a string. It should be of type `int64` to handle both positive and negative values efficiently.
• `base`: The `base` parameter determines the numeric base for the string representation. We can choose values such as 2, 8, 10, or 16 to represent binary, octal, decimal, or hexadecimal respectively.

Now, let’s see an example that demonstrates the usage of `FormatInt`:

``````package main

import (
"fmt"
"strconv"
"reflect"
)

func main() {
num := 42
base := 10

str := strconv.FormatInt(int64(num), base)
fmt.Println("String:", str)

// Verifying the converted value type
fmt.Println("Type of str:", reflect.TypeOf(str))
}``````

In this code example, we define an integer variable `num` with a value of 42, and the `base` variable is set to 10 for decimal representation. By calling `strconv.FormatInt`, passing `int64(num)` and `base` as arguments, we convert the integer `num` to a string. The resulting string is stored in the variable `str`.

To verify the type of the converted value, we utilize the `reflect.TypeOf` function from the reflect package. This function helps us determine the type of any given variable. In our example, we print the type of `str` to the console.

When we run the code, the output will be:

``````String: 42
Type of str: string``````

As we can see, the integer `42` has been successfully converted to a string representation. The type of `str` is confirmed as a string through the use of `reflect.TypeOf`.

#### Base in FormatInt

We have successfully converted the int/int64 to a string in Golang using the FormatInt function. However, you might be wondering, what is the purpose of the base parameter in this function? Well, let’s delve into it and find out.

The base parameter in the `FormatInt` function allows you to specify the numerical base for the resulting string representation of the integer. In simpler terms, it determines the numbering system used to represent the converted string. By choosing different base values, you can obtain strings in various formats. Let’s explore a few common bases and their implications:

1. Base 2 (Binary): This base represents the number in binary form, consisting of only 0s and 1s. For example, the integer 42 in base 2 would be represented as “101010”.
2. Base 8 (Octal): In this case, the number is represented using digits ranging from 0 to 7. For instance, the integer 42 in base 8 would be represented as “52”.
3. Base 10 (Decimal): Base 10 is the most common numbering system we use in our daily lives. It represents numbers using digits ranging from 0 to 9. The integer 42 in base 10 remains the same: “42”.
4. Base 16 (Hexadecimal): Hexadecimal is often used in computing and programming. It uses digits from 0 to 9, followed by letters A to F, to represent numbers. For example, the integer 42 in base 16 would be represented as “2A”.
##### Example

Now, let’s consider an example to illustrate the different bases in action:

``````package main

import (
"fmt"
"strconv"
)

func main() {
num := 42

fmt.Println("Decimal:", strconv.FormatInt(int64(num), 10))
fmt.Println("Binary:", strconv.FormatInt(int64(num), 2))
fmt.Println("Octal:", strconv.FormatInt(int64(num), 8))
}``````

In this code snippet, we start with the decimal representation of the integer 42. By passing the integer and the desired base to the `FormatInt` function, we obtain the corresponding string representation for each base.

The output of the code will be as follows:

``````Decimal: 42
Binary: 101010
Octal: 52

### Golang int/int64 to String Using Sprintf

Let’s explore another method to convert an integer to a string in Golang, and this time we’ll turn our attention to the fmt package. You might be surprised to know that our beloved fmt package offers a function called Sprintf that can assist us in achieving this conversion. Yes, you heard it right! So, let’s dive into the details of the Sprintf function and discover how it can be utilized to convert an int to a string.

The `fmt.Sprintf()` function is part of the fmt package and allows us to format strings using placeholders and values. It provides a powerful way to create formatted strings with dynamic content. One of its capabilities is the ability to convert an integer to a string representation.

Let’s take a look at an example to understand the usage of `fmt.Sprintf()` for converting an int to a string:

``````package main

import "fmt"

func main() {
num := 42
str := fmt.Sprintf("%d", num)
fmt.Println("Integer:", num)
fmt.Println("String:", str)
}``````

In the above code snippet, we have an integer variable called num, which holds the value 42. By using `fmt.Sprintf("%d", num)`, we format the value of num as a string and store it in the variable str. Finally, we print both the original integer and its string representation to the console.

Isn’t it fascinating how `fmt.Sprintf()` allows us to perform the int-to-string conversion effortlessly?

## Wrapping Up

In conclusion, we have explored different methods to convert integers to strings in Golang. By using functions like `strconv.Itoa()`, `fmt.Sprintf()`, and `strconv.FormatInt()`, you can easily perform these conversions in your code.

Remember to handle errors and consider formatting options based on your specific needs. By mastering this skill, you enhance your abilities as a Golang developer. So go ahead, apply these techniques, and enjoy coding with confidence!

How to convert an int to a string in Golang?

To convert an integer to a string in Golang, you can use functions like `strconv.Itoa()`, `fmt.Sprintf()`, or `strconv.FormatInt()`. These functions allow you to easily perform the conversion and obtain the string representation of the integer.

Why is the string() function not used for int-to-string conversion in Golang?

The string() conversion function in Golang is not used for converting an int to a string because it converts the ASCII value of the integer to its corresponding character, rather than providing the string representation of the integer itself.

What is the difference between strconv.Itoa() and strconv.FormatInt() function?

The strconv.Itoa function is used to convert an integer to a string in base 10, while strconv.FormatInt provides more formatting options, allowing you to customize the base and format of the resulting string.

Can fmt.Sprintf convert an integer to a string in Golang?

Yes, `fmt.Sprintf()` can convert an integer to a string in Golang. By using the “%d” placeholder, you can specify that an integer should be converted to its string representation.

## Reference

1. The Go Programming Language Specification: https://golang.org/ref/spec
2. The `strconv` Package: https://golang.org/pkg/strconv/