The strconv package converts Go values to and from string representations for numbers and booleans. Use ParseInt, ParseFloat, or Atoi to convert strings to numbers, and Itoa, FormatFloat, or FormatBool to convert numbers to strings.
package main
import (
"fmt"
"strconv"
)
func main() {
// String to int
i, err := strconv.Atoi("42")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Int:", i)
// Int to string
s := strconv.Itoa(i)
fmt.Println("String:", s)
// String to float
f, err := strconv.ParseFloat("3.14", 64)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Float:", f)
// Float to string
sf := strconv.FormatFloat(f, 'f', 2, 64)
fmt.Println("Float String:", sf)
// String to bool
b, err := strconv.ParseBool("true")
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Bool:", b)
// Bool to string
sb := strconv.FormatBool(b)
fmt.Println("Bool String:", sb)
}