Sobes.tech
Junior

How to convert a string to an integer and vice versa?

sobes.tech AI

Answer from AI

The strconv package is used for converting strings to integers.

import (
	"fmt"
	"strconv"
)

func main() {
	s := "123"
	i, err := strconv.Atoi(s) // Atoi is short for ASCII to integer
	if err != nil {
		fmt.Println("Conversion error:", err)
		return
	}
	fmt.Printf("String \"%s\" converted to number %d\n", s, i)

	// Conversion to int64
	s64 := "9223372036854775807"
	i64, err := strconv.ParseInt(s64, 10, 64) // string, base, bitSize
	if err != nil {
		fmt.Println("Conversion error:", err)
		return
	}
	fmt.Printf("String \"%s\" converted to number %d (int64)\n", s64, i64)
}

The strconv package is also used for converting integers to strings.

import (
	"fmt"
	"strconv"
)

func main() {
	i := 123
	s := strconv.Itoa(i) // Itoa is short for integer to ASCII
	fmt.Printf("Number %d converted to string \"%s\"\n", i, s)

	// Conversion of int64 to string
	i64 := int64(9223372036854775807)
	s64 := strconv.FormatInt(i64, 10) // number, base
	fmt.Printf("Number %d (int64) converted to string \"%s\"\n", i64, s64)
}