Go core
Browse topics

Number and string conversion with strconv

Version
1.27
Review
Draft

Summary#

strconv.Atoi and Itoa convert between decimal strings and int. ParseInt also takes a base and a bit size. A failed parse returns a *strconv.NumError that records the input and reason.

Syntax#

go
n, err := strconv.Atoi("42")
wide, err := strconv.ParseInt("ff", 16, 64)
text := strconv.Itoa(n)
enabled, err := strconv.ParseBool("true")

Example#

go
package main

import (
	"errors"
	"fmt"
	"strconv"
)

func main() {
	n, err := strconv.Atoi("42")
	fmt.Println(n+1, err)

	_, err = strconv.Atoi("4x2")
	fmt.Println(err)
	fmt.Println(errors.Is(err, strconv.ErrSyntax))

	small, err := strconv.ParseInt("300", 10, 8)
	fmt.Println(small, errors.Is(err, strconv.ErrRange))

	var numberError *strconv.NumError
	if errors.As(err, &numberError) {
		fmt.Println(numberError.Func, numberError.Num)
	}

	mask, err := strconv.ParseInt("0xff", 0, 64)
	fmt.Println(mask, err)
	_, err = strconv.ParseBool("yes")
	fmt.Println(err != nil)
	fmt.Println("port " + strconv.Itoa(8080))
}

Expected output#

Text
43 <nil>
strconv.Atoi: parsing "4x2": invalid syntax
true
127 true
ParseInt 300
255 <nil>
true
port 8080

Common mistakes#

string(65) yields "A", the character for that code point. Use strconv.Itoa(65) for "65". Check parse errors before using the value. An out-of-range signed parse returns the nearest limit of the requested size. Atoi uses the platform's int size. Use ParseInt with an explicit bit size for a portable range. Its result type is always int64.

Version applicability#

The conversion functions date back to Go 1.0. errors.As and errors.Is arrived in Go 1.13. The complete example requires Go 1.14 because matching ErrSyntax and ErrRange relies on NumError.Unwrap.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0