Go strconv Package

Convert between strings and numbers, booleans, and quoted representations โ€” the bridge between text and typed values.

Atoi / Itoa ParseInt / FormatInt ParseFloat / FormatFloat ParseBool / FormatBool Quote / Unquote AppendInt
๐Ÿ”

Atoi & Itoa

๐Ÿ’ก
Atoi and Itoa are convenience wrappers around ParseInt and FormatInt for the common case of base-10 int. Use them when you just need a quick int/string round-trip.
Atoi โ€” string to int Atoi
// Atoi โ€” "ASCII to integer"
n, err := strconv.Atoi("42")
// n=42, err=nil

n, err = strconv.Atoi("-17")
// n=-17, err=nil

n, err = strconv.Atoi("abc")
// n=0, err=*NumError

// Typical use: parsing CLI args or env vars
port, err := strconv.Atoi(os.Getenv("PORT"))
if err != nil {
    port = 8080
}
Itoa โ€” int to string Itoa
// Itoa โ€” "integer to ASCII"
s := strconv.Itoa(42)      // "42"
s  = strconv.Itoa(-17)     // "-17"
s  = strconv.Itoa(0)       // "0"

// Common uses
id := strconv.Itoa(userID)
filename := "page-" + strconv.Itoa(pageNum) + ".html"

// Note: fmt.Sprintf("%d", n) is equivalent but slower
// Itoa is the idiomatic choice for int โ†’ string
๐Ÿ”ข

Integers โ€” Parse & Format

ParseInt โ€” parse with base and bit size ParseInt
// ParseInt(s, base, bitSize) โ†’ int64, error
// base: 0 (detect from prefix), 2โ€“36; bitSize: 0,8,16,32,64

strconv.ParseInt("42", 10, 64)    // 42, nil
strconv.ParseInt("-42", 10, 64)   // -42, nil
strconv.ParseInt("ff", 16, 64)    // 255, nil  โ€” hex
strconv.ParseInt("111", 2, 64)    // 7, nil    โ€” binary
strconv.ParseInt("17", 8, 64)     // 15, nil   โ€” octal

// base 0 โ€” auto-detect from prefix
strconv.ParseInt("0xff", 0, 64)   // 255 โ€” 0x prefix โ†’ hex
strconv.ParseInt("0b1010", 0, 64) // 10  โ€” 0b prefix โ†’ binary
strconv.ParseInt("0o17", 0, 64)   // 15  โ€” 0o prefix โ†’ octal

// ParseUint โ€” unsigned only
strconv.ParseUint("255", 10, 8)   // 255, nil  โ€” fits in uint8
strconv.ParseUint("256", 10, 8)   // 0, ErrRange โ€” overflows uint8
FormatInt โ€” integer to string in any base FormatInt
// FormatInt(i int64, base int) โ†’ string
strconv.FormatInt(255, 10)   // "255"
strconv.FormatInt(255, 16)   // "ff"
strconv.FormatInt(255, 2)    // "11111111"
strconv.FormatInt(255, 8)    // "377"
strconv.FormatInt(-42, 10)   // "-42"

// FormatUint โ€” unsigned
strconv.FormatUint(255, 16)  // "ff"
strconv.FormatUint(255, 2)   // "11111111"
๐ŸŒŠ

Floats โ€” Parse & Format

โ„น๏ธ
ParseFloat always returns a float64. Pass bitSize=32 to constrain the result to float32 range โ€” the returned value is still float64 but safe to cast.
ParseFloat ParseFloat
// ParseFloat(s, bitSize) โ†’ float64, error
strconv.ParseFloat("3.14", 64)     // 3.14, nil
strconv.ParseFloat("-2.71", 64)    // -2.71, nil
strconv.ParseFloat("1.5e3", 64)    // 1500, nil
strconv.ParseFloat("NaN", 64)       // NaN, nil
strconv.ParseFloat("Inf", 64)       // +Inf, nil
strconv.ParseFloat("abc", 64)       // 0, ErrSyntax

// Parse as float32 precision
v, _ := strconv.ParseFloat("3.14", 32)
f32 := float32(v)
FormatFloat FormatFloat
// FormatFloat(f, fmt, prec, bitSize)
// fmt: 'f' decimal, 'e' scientific, 'g' shortest, 'x' hex
// prec: decimal places (-1 = shortest representation)

f := 3.14159
strconv.FormatFloat(f, 'f', 2, 64)  // "3.14"
strconv.FormatFloat(f, 'f', 4, 64)  // "3.1416"
strconv.FormatFloat(f, 'e', 3, 64)  // "3.142e+00"
strconv.FormatFloat(f, 'g', -1, 64) // "3.14159" (shortest)
strconv.FormatFloat(f, 'g', 3, 64)  // "3.14"
โœ…

Booleans โ€” Parse & Format

ParseBool โ€” flexible boolean parsing ParseBool
// Accepts many truthy/falsy string forms
strconv.ParseBool("true")   // true, nil
strconv.ParseBool("TRUE")   // true, nil
strconv.ParseBool("1")      // true, nil
strconv.ParseBool("t")      // true, nil
strconv.ParseBool("T")      // true, nil

strconv.ParseBool("false")  // false, nil
strconv.ParseBool("FALSE")  // false, nil
strconv.ParseBool("0")      // false, nil
strconv.ParseBool("f")      // false, nil

strconv.ParseBool("yes")    // false, ErrSyntax
FormatBool & usage pattern FormatBool
strconv.FormatBool(true)    // "true"
strconv.FormatBool(false)   // "false"

// Common pattern: parse feature flags from env
isEnabled := func(key string) bool {
    v, err := strconv.ParseBool(os.Getenv(key))
    return err == nil && v
}

if isEnabled("FEATURE_DARK_MODE") {
    // enable dark mode
}
๐Ÿ’ฌ

Quote & Unquote

โ„น๏ธ
Quote produces a Go string literal with escape sequences for special characters โ€” useful for logging, debugging, or generating Go source. Unquote reverses it.
Quote โ€” wrap in double quotes with escaping Quote
strconv.Quote("Hello, World")   // `"Hello, World"`
strconv.Quote("tab\there")      // `"tab\there"`
strconv.Quote("new\nline")      // `"new\nline"`
strconv.Quote(`say "hi"`)       // `"say \"hi\""`
strconv.Quote("ๆ—ฅๆœฌ่ชž")           // `"ๆ—ฅๆœฌ่ชž"` (printable Unicode kept)

// QuoteToASCII โ€” escapes non-ASCII as \uXXXX
strconv.QuoteToASCII("ๆ—ฅๆœฌ่ชž")    // `"ๆ—ฅๆœฌ่ชž"`

// QuoteRune โ€” quote a single rune
strconv.QuoteRune('A')          // `'A'`
strconv.QuoteRune('\n')         // `'\n'`
strconv.QuoteRune('ๆ—ฅ')          // `'ๆ—ฅ'`
Unquote โ€” parse a quoted string literal Unquote
// Unquote interprets a Go string literal
s, err := strconv.Unquote(`"Hello\nWorld"`)
// s = "Hello\nWorld" (actual newline), err = nil

s, err = strconv.Unquote(`"tab\there"`)
// s = "tab\there" (actual tab), err = nil

s, err = strconv.Unquote(`"say \"hi\""`)
// s = `say "hi"`, err = nil

// Backtick (raw) strings also work
s, err = strconv.Unquote("`raw\nstring`")
// s = "raw\\nstring" (backslash not interpreted)
โš ๏ธ

Error Handling

NumError โ€” inspect parse failures NumError
// Parse functions return *strconv.NumError on failure
_, err := strconv.Atoi("abc")
if err != nil {
    var ne *strconv.NumError
    if errors.As(err, &ne) {
        ne.Func  // "Atoi"
        ne.Num   // "abc"  (the input)
        ne.Err   // strconv.ErrSyntax or strconv.ErrRange
    }
}

// Two sentinel errors to check for
errors.Is(err, strconv.ErrSyntax)  // invalid characters
errors.Is(err, strconv.ErrRange)   // value out of range for type

// ErrRange example
_, err = strconv.ParseInt("999", 10, 8)  // overflows int8 (max 127)
errors.Is(err, strconv.ErrRange)         // true
Patterns for parsing user input Patterns
// Parse with default fallback
parseInt := func(s string, def int) int {
    n, err := strconv.Atoi(s)
    if err != nil {
        return def
    }
    return n
}
port := parseInt(os.Getenv("PORT"), 8080)

// Parse with range validation
raw := os.Getenv("WORKERS")
workers, err := strconv.Atoi(raw)
if err != nil || workers < 1 || workers > 100 {
    return fmt.Errorf("WORKERS must be 1-100, got %q", raw)
}
โž•

Append Variants

๐Ÿ’ก
The Append* variants write directly into a []byte without allocating a new string. Use them in tight loops or when building byte slices incrementally.
AppendInt, AppendFloat, AppendBool โ€” zero-alloc formatting Append*
buf := []byte("value=")
buf = strconv.AppendInt(buf, 42, 10)
// buf = "value=42"

buf = append(buf, ' ')
buf = strconv.AppendFloat(buf, 3.14, 'f', 2, 64)
// buf = "value=42 3.14"

buf = append(buf, ' ')
buf = strconv.AppendBool(buf, true)
// buf = "value=42 3.14 true"

buf = strconv.AppendQuote(buf[:0], "hello\nworld")
// buf = `"hello\nworld"`

fmt.Println(string(buf))
๐Ÿ“‹

Quick Reference

FunctionReturnsDescription
strconv.Atoi(s)int, errorParse base-10 string to int
strconv.Itoa(i)stringFormat int to base-10 string
strconv.ParseInt(s, base, bitSize)int64, errorParse signed integer in any base (2โ€“36); bitSize limits range
strconv.ParseUint(s, base, bitSize)uint64, errorParse unsigned integer in any base
strconv.FormatInt(i, base)stringFormat int64 in any base
strconv.FormatUint(u, base)stringFormat uint64 in any base
strconv.ParseFloat(s, bitSize)float64, errorParse decimal or scientific notation float
strconv.FormatFloat(f, fmt, prec, bitSize)stringFormat float; fmt='f'/'e'/'g'/'x', prec=-1 for shortest
strconv.ParseBool(s)bool, errorParse "1","t","true","T","TRUE","false","0","f","F","FALSE"
strconv.FormatBool(b)string"true" or "false"
strconv.Quote(s)stringWrap in double quotes, escape special chars
strconv.QuoteToASCII(s)stringLike Quote but escapes non-ASCII as \uXXXX
strconv.QuoteRune(r)stringSingle-quote a rune with escaping
strconv.Unquote(s)string, errorParse a Go string or char literal
strconv.AppendInt(dst, i, base)[]byteAppend formatted int to byte slice
strconv.AppendFloat(dst, f, fmt, prec, bitSize)[]byteAppend formatted float to byte slice
strconv.AppendBool(dst, b)[]byteAppend "true" or "false" to byte slice
strconv.AppendQuote(dst, s)[]byteAppend quoted string to byte slice
strconv.ErrSyntaxerrorSentinel: input is not valid for the type
strconv.ErrRangeerrorSentinel: value overflows the target type