Go by Example: Number Parsing

The strconv package in Go provides functions for converting strings to and from various numerical types, including integers and floats.

Here’s an example that demonstrates how to use the strconv package to parse numbers from strings:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	// Parse an int from a string
	intValue, err := strconv.Atoi("42")
	if err != nil {
		fmt.Println("Error parsing int:", err)
	} else {
		fmt.Println("Int value:", intValue)
	}

	// Parse a float from a string
	floatValue, err := strconv.ParseFloat("3.14", 64)
	if err != nil {
		fmt.Println("Error parsing float:", err)
	} else {
		fmt.Println("Float value:", floatValue)
	}

	// Parse an int from a string in a given base (2, 8, 10, or 16)
	base := 16
	intValue, err = strconv.ParseInt("ff", base, 64)
	if err != nil {
		fmt.Println("Error parsing int with base", base, ":", err)
	} else {
		fmt.Println("Int value in base", base, ":", intValue)
	}
}

In this example, the strconv.Atoi function is used to parse an int from a string, and the strconv.ParseFloat function is used to parse a float from a string. If the parsing fails, an error is returned.

The strconv.ParseInt function is also demonstrated, which allows you to parse an int from a string in a given base (2, 8, 10, or 16). If the parsing fails, an error is returned.

The output of this program will be something like:

Int value: 42
Float value: 3.14
Int value in base 16: 255

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *