Golang Integer String Conversion Tutorial Image

Golang Integer String Conversion Tutorial

In this tutorial we briefly look at how one can convert an integer to string and back again in GoLang. In order to do this we’ll be using the ‘strconv’ package and the Atoi and Itoa functions.

Full documentation of the strconv package can be found here: Strconv Package

String to Integer Conversion

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
func strToIntConversion() {
	fmt.Println("String to Integer Value Conversion")

	var ourInteger int
	// use the strconv package to convert our string '12345' to an integer value
	ourInteger, err := strconv.Atoi("12345")

	// if there has been an error then handle it here
	if err != nil {
		fmt.Println(err)
	}

	// this should print out 12346
	fmt.Println(ourInteger + 1)

}

Integer to String Conversion

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
func intToStringConversion() {
	fmt.Println("integer to string conversion")

	var ourString string

	ourString = strconv.Itoa(12345)

	// print out our string value
	fmt.Println(ourString)

}

Conclusion

Full Source Code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package main

import (
	"fmt"
	"strconv"
)

func strToIntConversion() {
	fmt.Println("String to Integer Value Conversion")

	var ourInteger int
	// use the strconv package to convert our string '12345' to an integer value
	ourInteger, err := strconv.Atoi("12345")

	// if there has been an error then handle it here
	if err != nil {
		fmt.Println(err)
	}

	// this should print out 12346
	fmt.Println(ourInteger + 1)
}


func intToStringConversion() {
	fmt.Println("integer to string conversion")

	var ourString string

	ourString = strconv.Itoa(12345)

	// print out our string value
	fmt.Println(ourString)

}


func main() {
	strToIntConversion()
	intToStringConversion()
}
Was This Post Helpful?
Submit a PR: Edit on Github