How to convert numbers to strings in Go

Converting a number to a string is easy in most programming languages, and its no different in Go

When attempting an integer to string conversion you should avoid plain type conversions shown below. The number will be interpreted as a Unicode code point and the result will be the character represented by that Unicode code point.

func main() {
	str := string(75)
	fmt.Println(str) // K
}

Instead, use the strconv.Itoa method which was made for this purpose. It simply takes an integer value and returns its string representation.

func main() {
	str := strconv.Itoa(75)
	fmt.Println(str) // 75
}

You can also use fmt.Sprintf which is especially handy in the context of formatting a string.

func main() {
	str1 := fmt.Sprintf("%d", 75)
	str2 := fmt.Sprintf("%f", 123.456)
	fmt.Println(str1) // 75
	fmt.Println(str2) // 123.456000
}

By default, floating point numbers have six digits after the decimal point. If the number you pass has less than that amount, it will be padded with zeros (as shown above). You can also specify your desired width:

func main() {
	str := fmt.Sprintf("%.3f", 123.456)
	fmt.Println(str) // 123.456
}

Conclusion

Converting a number to a string is quite easy in Go. Just use strconv.Itoa or fmt.Sprintf depending on the use case, and avoid a plain type conversion. If you’re looking to convert a string to an integer, this article gives the answers you seek.