Skip to main content
Parsing numbers from strings is a basic but common task in many programs. Here’s how to do it in Go using the strconv package.

Parsing Floats

The 64 parameter tells how many bits of precision to parse:
f, _ := strconv.ParseFloat("1.234", 64)
fmt.Println(f)
// Output: 1.234

Parsing Integers

For ParseInt, the 0 means infer the base from the string. 64 requires that the result fit in 64 bits:
i, _ := strconv.ParseInt("123", 0, 64)
fmt.Println(i)
// Output: 123

Hexadecimal Numbers

ParseInt recognizes hex-formatted numbers:
d, _ := strconv.ParseInt("0x1c8", 0, 64)
fmt.Println(d)
// Output: 456

Parsing Unsigned Integers

ParseUint is available for unsigned integers:
u, _ := strconv.ParseUint("789", 0, 64)
fmt.Println(u)
// Output: 789

Convenience Function: Atoi

Atoi is a convenience function for basic base-10 int parsing:
k, _ := strconv.Atoi("135")
fmt.Println(k)
// Output: 135

Error Handling

Parse functions return an error on bad input:
_, e := strconv.Atoi("wat")
fmt.Println(e)
// Output: strconv.Atoi: parsing "wat": invalid syntax
Always check the error return value when parsing user input to handle invalid data gracefully.

Parse Functions

ParseFloat
func(s string, bitSize int) (float64, error)
Parses a floating-point number. bitSize: 32 or 64
ParseInt
func(s string, base int, bitSize int) (int64, error)
Parses an integer. base: 0 (auto-detect), 2-36. bitSize: 0, 8, 16, 32, 64
ParseUint
func(s string, base int, bitSize int) (uint64, error)
Parses an unsigned integer. base: 0 (auto-detect), 2-36. bitSize: 0, 8, 16, 32, 64
Atoi
func(s string) (int, error)
Shorthand for ParseInt(s, 10, 0), converted to int

Base Detection

When base is 0, ParseInt auto-detects the base:
Hexadecimal: 0x1c8 → 456
Octal: 0o755 → 493
Binary: 0b1010 → 10
Decimal: 123 → 123

Number Formatting

To convert numbers to strings, use the Format functions:
// Format integer to string
s := strconv.FormatInt(123, 10)
fmt.Println(s) // Output: "123"

// Format float to string
f := strconv.FormatFloat(3.14, 'f', 2, 64)
fmt.Println(f) // Output: "3.14"

// Shorthand for base-10 int to string
i := strconv.Itoa(456)
fmt.Println(i) // Output: "456"

Package Reference

Build docs developers (and LLMs) love