The strconv Package
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
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))
}
Login to try C/C++/Java/PHP code in the editor
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
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)
}
Login to try C/C++/Java/PHP code in the editor
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
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)
}
Login to try C/C++/Java/PHP code in the editor
- Ignoring the error returned by strconv.Atoi/ParseFloat, assuming the input string is always valid.
- Using strconv.Itoa on a float, when Itoa only accepts int -- floats need strconv.FormatFloat instead.
- Forgetting strconv.ParseBool accepts several textual forms ("1", "t", "true", etc.), not just the literal words true/false.
- 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.
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: