How to Convert String to Int in Golang

1. Introduction

In Go, string-to-integer conversion is done using functions from the strconv package. The Atoi (ASCII to integer) function is commonly used for base-10 numbers, while ParseInt allows for different bases and sizes of integers. This post will guide you through converting a string to an integer in Go.

2. Program Steps

1. Import the strconv package.

2. Use the strconv.Atoi function to convert a string to an integer.

3. Handle any potential errors that arise from the conversion.

4. Use strconv.ParseInt for converting strings with bases other than 10 or for sizes other than int.

3. Code Program

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Example string that represents an integer
	strNumber := "42"

	// Step 2: Use strconv.Atoi to convert string to int
	intNumber, err := strconv.Atoi(strNumber)
	if err != nil {
		// Step 3: Handle conversion error
		fmt.Println("Conversion error:", err)
	} else {
		fmt.Printf("Converted integer: %d\n", intNumber)
	}

	// Example string with a number in a different base
	binaryNumber := "101010"

	// Step 4: Use strconv.ParseInt for more complex conversions
	if intBinaryNumber, err := strconv.ParseInt(binaryNumber, 2, 64); err != nil {
		fmt.Println("Conversion error:", err)
	} else {
		fmt.Printf("Converted binary to integer: %d\n", intBinaryNumber)
	}
}

Output:

Converted integer: 42
Converted binary to integer: 42

Explanation:

1. package main - The package declaration for the Go program.

2. import "fmt" and import "strconv" - Importing packages for formatted output and string conversion, respectively.

3. strNumber is a string that holds a number in base-10 format.

4. strconv.Atoi(strNumber) attempts to convert strNumber to an integer. It returns two values: the converted integer and an error value.

5. An if statement checks for errors in the conversion. If an error is found, it prints an error message; otherwise, it prints the converted integer.

6. binaryNumber is a string that holds a binary number.

7. strconv.ParseInt(binaryNumber, 2, 64) converts binaryNumber from base 2 to an integer. The third argument 64 specifies the size of the integer.

8. Like with Atoi, ParseInt also returns an integer and an error, which are handled similarly.

9. The output confirms the successful conversion of both the decimal string "42" and the binary string "101010" to the integer 42.


Comments