Converts between strings and basic data types: integers, floats, and booleans. Essential for parsing command-line arguments, config files, and HTTP query parameters. All parse functions return both a value and an error — always check the error.
Import: import "strconv" | Docs: pkg.go.dev/strconv
| Name | Signature / Value | Description |
|---|---|---|
| strconv.Atoi | func Atoi(s string) (int, error) | Parse decimal string to int (shorthand for ParseInt base 10) |
| strconv.Itoa | func Itoa(i int) string | Convert int to decimal string |
| strconv.ParseInt | func ParseInt(s string, base, bitSize int) (int64, error) | Parse string to int64 in given base (2–36) |
| strconv.ParseUint | func ParseUint(s string, base, bitSize int) (uint64, error) | Parse string to uint64 |
| strconv.ParseFloat | func ParseFloat(s string, bitSize int) (float64, error) | Parse string to float64 |
| strconv.ParseBool | func ParseBool(s string) (bool, error) | Parse '1','t','T','TRUE','true','TRUE','0','f','F' etc. |
| strconv.FormatInt | func FormatInt(i int64, base int) string | Format int64 as string in given base |
| strconv.FormatFloat | func FormatFloat(f float64, fmt byte, prec, bitSize int) string | Format float64 as string |
| strconv.FormatBool | func FormatBool(b bool) string | Return 'true' or 'false' |
| strconv.AppendInt | func AppendInt(dst []byte, i int64, base int) []byte | Append int64 string to byte slice |
| strconv.Quote | func Quote(s string) string | Return double-quoted Go string literal |
| strconv.Unquote | func Unquote(s string) (string, error) | Interpret s as a quoted Go string literal |
| strconv.ErrRange | var ErrRange error | Returned when value out of range for target type |
| strconv.ErrSyntax | var ErrSyntax error | Returned when string not in expected format |
Save as main.go inside any directory and run with go run main.go. No extra packages to install — all standard library.
package main
import (
"fmt"
"strconv"
)
func main() {
// String → int
n, err := strconv.Atoi("42")
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Printf("Atoi: %d (type %T)\n", n, n)
}
// int → string
s := strconv.Itoa(12345)
fmt.Printf("Itoa: %q\n", s)
// ParseFloat
f, err := strconv.ParseFloat("3.14159", 64)
if err == nil {
fmt.Printf("ParseFloat: %.5f\n", f)
}
// ParseBool
b, _ := strconv.ParseBool("true")
fmt.Printf("ParseBool: %v\n", b)
// ParseInt with base
hex, _ := strconv.ParseInt("FF", 16, 64)
bin, _ := strconv.ParseInt("1010", 2, 64)
fmt.Printf("ParseInt hex=0xFF → %d\n", hex)
fmt.Printf("ParseInt bin=1010 → %d\n", bin)
// FormatFloat
fs := strconv.FormatFloat(3.14159265, 'f', 4, 64)
fmt.Println("FormatFloat:", fs)
// Error handling best practice
if _, err := strconv.Atoi("not_a_number"); err != nil {
fmt.Println("Expected error:", err)
}
// Quote / Unquote
quoted := strconv.Quote("Hello\tWorld\n")
fmt.Println("Quoted:", quoted)
unquoted, _ := strconv.Unquote(quoted)
fmt.Println("Unquoted:", unquoted)
}
// go run main.go