← Back to Go Course | Chapter 14: Standard Library & HTTP | Lesson 2 of 10

The strconv Package

strconv is Go's translator between numbers and the text versions of numbers, converting back and forth carefully so nothing gets lost or misread.

String to Int and Back

strconv.Atoi parses a string as a base-10 integer, returning an error if it isn't valid, and strconv.Itoa does the reverse, converting an int into its string form.

Example: String to Int and Back

markup
package main

import (
	"fmt"
	"strconv"
)

func main() {
	n, err := strconv.Atoi("123")
	if err != nil {
		fmt.Println("parse error:", err)
		return
	}
	fmt.Println(n + 1)
	fmt.Println(strconv.Itoa(n + 1))
}

Parsing Floating-Point Numbers

strconv.ParseFloat converts a string into a float64, taking a bit-size argument (64 for float64) to control precision expectations during parsing.

Example: Parsing Floating-Point Numbers

markup
package main

import (
	"fmt"
	"strconv"
)

func main() {
	f, err := strconv.ParseFloat("3.14", 64)
	if err != nil {
		fmt.Println("parse error:", err)
		return
	}
	fmt.Println(f * 2)
}

Parsing Booleans

strconv.ParseBool recognizes several common textual representations of true and false (like "1"/"0", "t"/"f", "true"/"false"), converting any of them into a proper bool value.

Example: Parsing Booleans

markup
package main

import (
	"fmt"
	"strconv"
)

func main() {
	b, err := strconv.ParseBool("true")
	if err != nil {
		fmt.Println("parse error:", err)
		return
	}
	fmt.Println("parsed bool:", b)
}
Common Mistakes
  1. Ignoring the error returned by strconv.Atoi/ParseFloat, assuming the input string is always valid.
  2. Using strconv.Itoa on a float, when Itoa only accepts int -- floats need strconv.FormatFloat instead.
  3. Forgetting strconv.ParseBool accepts several textual forms ("1", "t", "true", etc.), not just the literal words true/false.
Chapter Summary
  • strconv.Atoi and strconv.Itoa convert between string and int.
  • strconv.ParseFloat and strconv.FormatFloat handle floating-point numbers, requiring a bit-size argument.
  • strconv.ParseBool converts strings like "true"/"1" into a bool.
  • Every strconv parsing function returns an error alongside the result, which should always be checked.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.