Saturday, July 27, 2024
Developer

Convert Int to String Golang

Hi sobat Kekasi. to convert Int variable to String. Go (Golang) already provides the “strconv” package library.

To convert an Integer value to a string in golang, we can use the FormatInt function from the strconv package.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	v := int64(-42)

	s10 := strconv.FormatInt(v, 10)
	fmt.Printf("%T, %v\n", s10, s10)

	s16 := strconv.FormatInt(v, 16)
	fmt.Printf("%T, %v\n", s16, s16)

}
Output:

string, -42
string, -2a

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.

So all you need is an integer value and the given integer base. There is a simpler function you can use if you want to convert an integer base to an ASCII string. namely Itoa.

package main

import (
	"fmt"
	"strconv"
)

func main() {
	i := 10
	s := strconv.Itoa(i)
	fmt.Printf("%T, %v\n", s, s)

}
Output:

string, 10

Itoa is equivalent to FormatInt(int64(i), 10).

Let’s practice. how can we use the Atoi and FormatInt functions to convert integers to ASCII

package main

import (
  "fmt"
  "strconv"
)

func main() {
  i := 10
  s1 := strconv.FormatInt(int64(i), 10)
  s2 := strconv.Itoa(i)
  fmt.Printf("%v, %v\n", s1, s2)
}

As you can see, the results are exactly the same. The expected output from the above code is as follows

10, 10

Leave a Reply