Parse and format with strconv
Parse and format with strconv
Use strconv for explicit conversions between textual representations and numeric or Boolean values. Atoi parses a decimal int; Itoa formats an int. ParseInt accepts a base and bit size and returns int64 plus an error. FormatInt converts an integer to text in the selected base.
package main
import ( "fmt" "strconv")
func main() { n, err := strconv.Atoi("42") fmt.Println(n, err == nil) fmt.Println(strconv.Itoa(n + 8)) _, err = strconv.Atoi("42kg") fmt.Println(err != nil)}Atoi requires a valid decimal integer string and checks the machine int range. It does not trim surrounding whitespace. Do not ignore errors and treat zero as failure: zero is itself valid input. Use strings.TrimSpace only if your input contract permits surrounding whitespace.
Expected output:
42 true50trueChoose a base and range
package main
import ( "errors" "fmt" "strconv")
func main() { n, err := strconv.ParseInt("ff", 16, 16) fmt.Println(n, err == nil, strconv.FormatInt(n, 2)) _, err = strconv.ParseInt("128", 10, 8) fmt.Println(errors.Is(err, strconv.ErrRange)) b, err := strconv.ParseBool("true") fmt.Println(b, err == nil)}Base 16 interprets ff as 255. Bit size 8 restricts a signed result to -128 through 127; an out-of-range result must not be used as success. ParseBool accepts documented spellings, not arbitrary truthy strings. For signed decimal data with a fixed range, choose the bit size explicitly rather than assuming int is 64 bits.
Expected output:
255 true 11111111truetrue trueTry it locally
Parse "1010" as a base-2 signed integer with bit size 16 and print its decimal text. Reject "102" as invalid binary input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Core library 02: Parse and format with strconv
Check the lesson objective before moving on.
What happens when ParseInt("128",10,8) is called?
Which function formats an int64 in base 16?