Go - Convert int value to string example

In this source code example, we will see different ways to convert int value to string in Golang with examples.

In Go, we can perform the int to string conversion with the strconv.FormatInt, strconv.Itoa, or fmt.Sprintf functions.

The strconv package implements conversions to and from string representations of basic data types.

Go - int to string with Itoa

In the example, we convert the number of fruits into a string to build a message. Later, we output the type of the fruits and n variable


package main

import (
    "fmt"
    "strconv"
)

func main() {

    var fruits int = 6

    n := strconv.Itoa(fruits)
    msg := "There are " + n + " fruits"
    fmt.Println(msg)

    fmt.Printf("%T\n", fruits)
    fmt.Printf("%T\n", n)
}

Output:

There are 6 fruits
int
string
Note that the Itoa is equivalent to FormatInt(int64(i), 10).

Go - int to string with strconv.FormatInt


package main

import (
    "fmt"
    "strconv"
)

func main() {

    var fruits int64 = 6

	// FormatInt returns the string representation of i in the given base,
	// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'
	// for digit values >= 10.

    n := strconv.FormatInt(fruits, 10)

    msg := "There are " + n + " fruits"
    fmt.Println(msg)
}

Output:

There are 6 fruits

Go int to string with fmt.Sprintf

The fmt.Sprintf formats a new string; it replaces the %d specifier with an integer value.


package main

import (
    "fmt"
)

func main() {

    var fruits int = 5

    msg := fmt.Sprintf("There are %d fruits", fruits)
    fmt.Println(msg)
}

Output:

There are 6 fruits

Comments