Go by Example

Number Parsing

strconv.Atoi and ParseInt for integers, ParseFloat for floats, FormatInt and Itoa for the reverse, and error handling on invalid input.

The strconv package converts between strings and numeric values. Atoi parses decimal text as an int; ParseInt and ParseFloat let you choose the base and result size. FormatInt and Itoa convert integers back to strings.

Every parse returns an error. Check it because zero is also a valid parsed number.

package main
 
import (
    "fmt"
    "strconv"
)
 
func main() {
    n, err := strconv.Atoi("42")
    if err != nil {
        panic(err)
    }
    fmt.Println(n)
 
    _, err = strconv.ParseInt("256", 10, 8)
    fmt.Println(err)
}

In production

Validate numeric input at the boundary and handle parse errors before the value enters business logic. ParseInt's bit size sets the allowed result range, so a valid number can still overflow the requested type. Prefer strconv over scanning formatted text for routine conversions.

Enjoyed this? Get more software craft delivered to your inbox.