Skip to content

Go Number Parsing

Parsing numbers from strings is a common task in Go, handled by the strconv package.

1. Integer Parsing

  • Atoi: A quick way to convert a string to a base-10 int.
  • ParseInt: Allows specifying a base (e.g., 2 for binary, 16 for hex) and a bit-size.
package main

import (
    "fmt"
    "strconv"
)

func main() {
    // 1. Simple base-10 integer
    i, _ := strconv.Atoi("123")
    fmt.Println(i)

    // 2. Hexadecimal (base 16)
    h, _ := strconv.ParseInt("0x1c", 0, 64)
    fmt.Println(h) // 28

    // 3. Binary (base 2)
    b, _ := strconv.ParseInt("101", 2, 64)
    fmt.Println(b) // 5
}

2. Float Parsing

Use ParseFloat to convert a string into a decimal number.

f, _ := strconv.ParseFloat("1.234", 64)
fmt.Println(f)

3. Converting to Strings

If you need to go the other way (Number -> String), use Itoa or FormatFloat.

s := strconv.Itoa(123)
fmt.Println(s) // "123"

Error Handling

Parsing functions return an error if the input is not a valid number. You should always check it.

1
2
3
4
_, err := strconv.Atoi("wat")
if err != nil {
    fmt.Println(err) // strconv.Atoi: parsing "wat": invalid syntax
}

Why use strconv?

  • Safety: Explicitly handles overflow and invalid characters.
  • Performance: Much faster than using fmt.Sscanf.
  • Control: You can specify exactly how many bits (32 or 64) the result should be.