Conversion with strconv
- Go course
- Beginner
- Lesson 59/90
- 4 min
Learn string-number conversions with strconv.
Conversion with strconv
The strconv package converts safely between numbers and text:
n, err := strconv.Atoi("42") // string → int
s := strconv.Itoa(42) // int → string
f, err := strconv.ParseFloat("3.14", 64)
b, err := strconv.ParseBool("true")
t := strconv.FormatFloat(3.14159, 'f', 2, 64) // "3.14"Functions converting text to numbers always return an error; user input may be invalid.
The error type
A conversion error is of type *strconv.NumError and says why it failed:
_, err := strconv.Atoi("on iki")
fmt.Println(err)
// strconv.Atoi: parsing "on iki": invalid syntax
_, err = strconv.Atoi("99999999999999999999")
// ... value out of rangeYou can check the cause with errors.Is(err, strconv.ErrSyntax) and strconv.ErrRange.
Practice Sum the inputs
Walk the inputs []string{"10", " 20 ", "otuz", "5"}; convert each with strconv.Atoi after strings.TrimSpace, skip the invalid ones and sum the valid ones. Print the sum and the number skipped on one line.
Starter code
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
// buraya yaz
}Sample solution
package main
import (
"fmt"
"strconv"
"strings"
)
func main() {
toplam, atlanan := 0, 0
for _, s := range []string{"10", " 20 ", "otuz", "5"} {
n, err := strconv.Atoi(strings.TrimSpace(s))
if err != nil {
atlanan++
continue
}
toplam += n
}
fmt.Println(toplam, atlanan)
}Expected output
35 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does <code>strconv.Atoi(" 42")</code> (with a leading space) return?
- 0 and a syntax error Correct answer
- 42 and nil
- A panic
- -42
Explanation: Atoi doesn't accept spaces; user input should first be cleaned with strings.TrimSpace.
2 Convert to a number
n, err := strconv.____("17")
n, err := strconv.Atoi("17")
Explanation: Atoi (ASCII to integer) converts text to an int.
3 Function and direction
| Term | Meaning |
|---|---|
strconv.Atoi |
string → int |
strconv.Itoa |
int → string |
strconv.ParseFloat |
string → float64 |
strconv.ParseBool |
string → bool |