Sobes.tech
Junior

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

sobes.tech AI

Answer from AI

The strconv package, along with the Atoi or ParseInt functions, is used to convert a string to an integer. To convert an integer to a string, the strconv package, Itoa, or FormatInt functions are used.

import "strconv"

func main() {
	// String to number conversion
	strNum := "123"
	intNum, err := strconv.Atoi(strNum) // Atoi returns int and error
	if err != nil {
		// handle error
	}

	intNum64, err := strconv.ParseInt("456", 10, 64) // ParseInt returns int64, base, bitSize
	if err != nil {
		// handle error
	}

	// Number to string conversion
	numToStr := 789
	strResult := strconv.Itoa(numToStr) // Itoa returns string

	num64ToStr := int64(1011)
	strResult64 := strconv.FormatInt(num64ToStr, 10) // FormatInt returns string, base
}

Main functions:

Function Description Return value Package
Atoi(s string) Converts a string to a decimal integer. (int, error) strconv
ParseInt(s string, base int, bitSize int) Converts a string to an integer of specified bit size and base. (int64, error) strconv
Itoa(i int) Converts a decimal integer to a string. string strconv
FormatInt(i int64, base int) Converts an integer of specified bit size to a string with a specified base. string strconv

Atoi is a convenient shorthand for ParseInt(s, 10, 0) with the result converted to int. Itoa is a shorthand for FormatInt(int64(i), 10).

When converting a string to a number, it is important to handle errors, as the string may contain non-numeric characters or exceed the data type's size.

How to convert a string to an integer and vice versa… - sobes.tech