Converting a string to number
How do I convert a string to number if possible in Go?
Go comes with a core package called strconv
which makes this task very
easy. You can convert a string to an integer and specify a base as well. You
also have the flexibility to define the size of bits into which the number
should fit into.
test_string_to_int.go
package main
import (
"fmt"
"strconv"
)
func handleError(err error) {
if err != nil {
fmt.Println(err)
}
}
func main() {
str := "123"
/*
The first argument to ParseInt is the string to be converted.
The second argument is the base to which the number is to be converted.
The third argument is the number of bits to which the number should fit.
*/
i, err := strconv.ParseInt(str, 10, 64)
handleError(err)
fmt.Printf("%T %d\n", i, i)
str = "invalidString123"
_, err = strconv.ParseInt(str, 10, 64)
handleError(err)
}
$ go run test_string_to_int.go
int64 123
strconv.ParseInt: parsing "invalidString123": invalid syntax
The strconv
package also contains functions such as ParseUint
and
ParseFloat
which convert a string to unsigned integer and floating point
numbers respectively.
test_string_to_float.go
package main
import (
"fmt"
"os"
"strconv"
)
func main() {
str := "123.123"
/*
The first argument to ParseInt is the string to be converted.
The second argument is the number of bits to which the number should fit.
*/
i, err := strconv.ParseFloat(str, 64)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Printf("%T %f\n", i, i)
}
$ go run test_string_to_float.go
float64 123.123000