How to Convert string to integer type in Go
Created
Modified
strconv.Atoi Function
Package strconv implements conversions to and from string representations of basic data types.
package main
import (
"fmt"
"strconv"
)
func main() {
i, err := strconv.Atoi("10") // i = 10
if err != nil {
//handle error
}
fmt.Printf("%T, %v\n", i, i)
//If the input string isn’t in the integer format, then the function returns zero.
i, err = strconv.Atoi("abc10") // i = 0
if err != nil {
//handle error
fmt.Println(err)
}
fmt.Printf("%T, %v\n", i, i)
i, err = strconv.Atoi("9223372036854775809") // i = 9223372036854775807
if err != nil {
//handle error
fmt.Println(err)
}
fmt.Printf("%T, %v\n", i, i)
}
int, 10 strconv.Atoi: parsing "abc10": invalid syntax int, 0 strconv.Atoi: parsing "9223372036854775809": value out of range int, 9223372036854775807
Atoi is equivalent to ParseInt(s, 10, 0), converted to type int.
strconv.ParseInt Function
ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to 64) and returns the corresponding value i.
package main
import (
"fmt"
"strconv"
)
func main() {
// func strconv.ParseInt(s string, base int, bitSize int) (i int64, err error)
// fastest
v64 := "-10"
if s, err := strconv.ParseInt(v64, 10, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
// contains invalid digits
v64 = "abc1"
if s, err := strconv.ParseInt(v64, 10, 64); err != nil {
fmt.Println(err)
fmt.Printf("%T, %v\n", s, s)
}
// func ParseUint(s string, base int, bitSize int) (uint64, error)
// ParseUint is like ParseInt but for unsigned numbers.
v64 = "100"
if s, err := strconv.ParseUint(v64, 10, 64); err == nil {
fmt.Printf("%T, %v\n", s, s)
}
}
int64, -10 strconv.ParseInt: parsing "abc1": invalid syntax int64, 0 uint64, 100
fmt.Sscanf Function
Sscanf scans the argument string, storing successive space-separated values into successive arguments as determined by the format. It returns the number of items successfully parsed. Newlines in the input must match newlines in the format.
package main
import "fmt"
func main() {
var name string
var car int
var dead int
// not terribly fast but most flexible
n, err := fmt.Sscanf("80-Car Pileup on Pennsylvania Highway Leaves 6 Dead", "%d-Car Pileup on %s Highway Leaves %d Dead", &car, &name, &dead)
if err != nil {
panic(err)
}
fmt.Printf("%d: %s, %d, %d\n", n, name, car, dead)
}
3: Pennsylvania, 80, 6