Number parsing
Context
Section titled “Context”Convert strings to numbers using the strconv package. The most common functions:
strconv.Atoi(s)– string toint(base 10)strconv.ParseInt(s, base, bitSize)strconv.ParseFloat(s, bitSize)strconv.ParseUint(s, base, bitSize)
Example
Section titled “Example”Parse an integer and a floating point number from strings.
Code example
Section titled “Code example”package main
import ( "fmt" "strconv")
func main() { s1 := "123" i, err := strconv.Atoi(s1) if err == nil { fmt.Println("Parsed int:", i) }
s2 := "3.14159" f, err := strconv.ParseFloat(s2, 64) if err == nil { fmt.Println("Parsed float:", f) }
// Hexadecimal hex := "FF" val, _ := strconv.ParseInt(hex, 16, 64) fmt.Printf("Hex %s = %d\n", hex, val)}Output
Section titled “Output”Parsed int: 123Parsed float: 3.14159Hex FF = 255