Number Parsing in Go

Go: Number Parsing

Go's strconv package provides functionality for converting strings to numbers of various types. The package includes functions for parsing integers, floats, and booleans.

How to parse an integer from a string in Go

Here's an example of how to parse an integer from a string:


    package main

    import (
        "fmt"
        "strconv"
    )

    func main() {
        str := "42"
        num, err := strconv.Atoi(str)
        if err != nil {
            fmt.Println("Failed to parse integer:", err)
            return
        }
        fmt.Println(num) // Output: 42
    }

In this example, the strconv.Atoi() function is used to parse the string "42" as an integer. The function returns two values: the parsed integer and an error. If the string cannot be parsed as an integer, the function returns an error.

Here are some other functions we can use to parse numbers in Go:

  • strconv.ParseInt(s string, base int, bitSize int) (int64, error): parses a string as a signed integer with the specified base (2 to 36) and bit size (0, 8, 16, 32, or 64).
  • strconv.ParseUint(s string, base int, bitSize int) (uint64, error): parses a string as an unsigned integer with the specified base (2 to 36) and bit size (0, 8, 16, 32, or 64).
  • strconv.ParseFloat(s string, bitSize int) (float64, error): parses a string as a float with the specified bit size (32 or 64).
  • strconv.ParseBool(s string) (bool, error): parses a string as a boolean value (true or false).

Note that if the string cannot be parsed as the specified type, the parsing functions return an error. You should always check for errors when parsing numbers from strings to avoid unexpected behavior in your program.

Previous Article

Next Article