Sling Academy
Home/Golang/Parsing Numbers from Strings in Go

Parsing Numbers from Strings in Go

Last updated: November 24, 2024

Parsing numbers from strings is a common task in software development. The Go programming language provides several ways to convert string data into numerical values effectively. This article will guide you through the basic to advanced practices for parsing numbers from strings in Go, covering functions from the Go standard library.

Basic Parsing with strconv.Atoi

The strconv package in Go contains a multitude of functions for string manipulations, one of which is strconv.Atoi. This function is used for converting strings to integers and is a good starting point for those learning Go.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "123"
    num, err := strconv.Atoi(str)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("The integer is %d\n", num)
    }
}

In this basic example, strconv.Atoi tries to convert a given string str into an integer. If conversion fails, an error message will be displayed.

Intermediate Parsing with strconv.ParseInt and strconv.ParseUint

strconv.ParseInt is a more versatile function that parses strings into integer types, including base and bit size.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    str := "-12"
    num, err := strconv.ParseInt(str, 10, 64) // Parses base 10 and assigns to a int64
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("The integer is %d\n", num)
    }
    
    unsignedStr := "12"
    unum, err := strconv.ParseUint(unsignedStr, 10, 64) // Parses base 10 unsigned
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("The unsigned integer is %d\n", unum)
    }
}

Both ParseInt and ParseUint allow you to specify the number base for conversion, which can be useful when working with non-base 10 numbers.

Advanced Parsing with strconv.ParseFloat

When it comes to floating-point numbers, strconv.ParseFloat provides the necessary functionality to parse strings as floats.

package main

import (
    "fmt"
    "strconv"
)

func main() {
    floatStr := "3.14159"
    fnum, err := strconv.ParseFloat(floatStr, 64) // Converts string to float64
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("The floating point number is %f\n", fnum)
    }
}

This example uses ParseFloat to convert a string representation of a floating-point number into an actual float64 variable.

Error Handling

Across all these examples, proper error handling is emphasized due to the potential of encountering invalid strings. You should always check and handle these errors to ensure the robustness of your Go applications.

In conclusion, Go offers a set of powerful utilities for number parsing through the strconv package. From simple integer conversion to more sophisticated base and float parsing, understanding these methods can significantly enhance your data processing capabilities with Go programs.

Next Article: Handling Division by Zero and Infinity in Go

Previous Article: Formatting Numbers for Output in Go

Series: Numbers and Math in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant