Open In App

How to fetch an Integer variable as String in GoLang?

Last Updated : 22 Jun, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

To fetch an Integer variable as String, Go provides strconv package which has methods that return a string representation of int variable. There is nothing like an integer variable is converted to a string variable, rather, you have to store integer value as a string in a string variable. Following are the functions used to convert an integer to string:

1. strconv.Itoa(): To convert an int to a decimal string.

// s == "60"
s := strconv.Itoa(60) 

2. strconv.FormatInt(): To format an int64 in a given base.

var n int64 = 60

s := strconv.FormatInt(n, 10)   // s == "60" (decimal)

s := strconv.FormatInt(n, 16)   // s == "3C" (hexadecimal)

3. strconv.FormatUint(): To return the string representation of x in the given base, i.e., 2 <= base <= 36.

fmt.Println(strconv.FormatUint(60, 2)) // 111100 (binary)
fmt.Println(strconv.FormatUint(60, 10)) // 60 (decimal)

Example 1:




package main
  
import (
    "fmt"
    "strconv"
)
  
func main() {
  
    var var_int int
    var_int = 23
  
    // Itoa() is the most common
    // conversion from int to string.
    s1 := strconv.Itoa(var_int)
    fmt.Printf("%T %v\n", s1, s1)
  
    // format 23 int base 10 -> 23
    s2 := strconv.FormatInt(int64(var_int), 10)
    fmt.Printf("%T %v\n", s2, s2)
  
    // return string representation
    // of 23 in base 10 -> 23
    s3 := strconv.FormatUint(uint64(var_int), 10)
    fmt.Printf("%T %v\n", s3, s3)
  
    // concatenating all string->s1,s2 and s3.
    fmt.Println("Concatenating all strings: ", s1+s2+s3)
}


Output:

string 23
string 23
string 23
Concatenating all strings: 232323

Example 2:




package main
  
import (
    "fmt"
    "strconv"
)
  
func main() {
  
    var var_int int
    var_int = 50
  
    // Itoa() is the most common 
    // conversion from int to string.
    s1 := strconv.Itoa(var_int)
    fmt.Printf("%T %v\n", s1, s1)
  
    // format 50 int base 2 ->110010
    s2 := strconv.FormatInt(int64(var_int), 2)
    fmt.Printf("%T %v\n", s2, s2)
  
    // return string representation
    // of 50 in base 16 -> 32
    s3 := strconv.FormatUint(uint64(var_int), 16)
    fmt.Printf("%T %v\n", s3, s3)
  
    // concatenating all
    // string->s1,s2 and s3.
    fmt.Println("Concatenating all strings: ", s1+s2+s3)
}


Output:

string 50
string 110010
string 32
Concatenating all strings: 5011001032


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads