strconv

Guided tour · Formatting & Strings · pkg.go.dev →

Convert between strings and numeric/boolean types. Lower-level and faster than fmt for pure conversion.

Convert numbers and bools to/from strings. Use this rather than fmt.Sscan for one-off parsing — strconv is faster and gives clearer errors.

String → int
n, err := strconv.Atoi("42")
Int → string
s := strconv.Itoa(42)
String → float
f, err := strconv.ParseFloat("3.14", 64)
Float → string
s := strconv.FormatFloat(3.14, 'f', -1, 64)
String → bool
b, err := strconv.ParseBool("true")
Quote / unquote
strconv.Quote(s); strconv.Unquote(s)

Integers

Atoi / Itoa — decimal shortcut

Atoi is Ascii-to-integer. Use when you have a plain base-10 int-sized value.

n, err := strconv.Atoi("42")
fmt.Println(n, err)

s := strconv.Itoa(-42)
fmt.Println(s)
Output
42 <nil>
-42

ParseInt / FormatInt — any base, any bit size

base=0 lets the prefix decide (0x=16, 0o=8, 0b=2, else 10). bitSize is the width to fit into.

n, _ := strconv.ParseInt("0xff", 0, 64)   // 255
m, _ := strconv.ParseInt("-10", 10, 8)    // -10 (fits int8)
_, err := strconv.ParseInt("300", 10, 8)  // value out of range

s := strconv.FormatInt(255, 16)           // "ff"
fmt.Println(n, m, err, s)
Output
255 -10 strconv.ParseInt: parsing "300": value out of range ff

ParseUint / FormatUint

u, _ := strconv.ParseUint("1010", 2, 64)  // 10
fmt.Println(u, strconv.FormatUint(10, 2)) // "1010"

Floats

ParseFloat — 32 or 64 bit

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

FormatFloat — formats 'g', 'f', 'e', etc.

prec=-1 means the smallest number of digits that round-trips exactly.

fmt.Println(strconv.FormatFloat(3.14159, 'f', 2, 64))  // 3.14
fmt.Println(strconv.FormatFloat(1e10, 'e', -1, 64))    // 1e+10
fmt.Println(strconv.FormatFloat(0.1, 'g', -1, 64))     // 0.1
Output
3.14
1e+10
0.1

Bool

ParseBool / FormatBool

ParseBool accepts 1, t, T, TRUE, true, True and the false equivalents.

b, _ := strconv.ParseBool("true")
fmt.Println(b, strconv.FormatBool(b))
Output
true true

Quoting

Quote / Unquote — Go-syntax strings

fmt.Println(strconv.Quote("hi\tthere"))      // "hi\tthere"
s, _ := strconv.Unquote(`"hi\tthere"`)
fmt.Println(s)                                // hi	there
Output
"hi\tthere"
hi	there

QuoteRune and AppendQuote — avoid allocations

Append* variants write into an existing []byte — great inside hot loops.

buf := []byte("msg=")
buf = strconv.AppendQuote(buf, "hi\n")
fmt.Println(string(buf))
Output
msg="hi\n"