How to convert a string to a number in Golang?
In Go language, you can use functions in the strconv package to convert strings to numbers. The specific implementation steps are as follows:
- import the strconv package: import “strconv”
- Convert using functions in the strconv package.
- Convert a string to an integer using the Atoi function: num, err := strconv.Atoi(str)
- Convert the string to an int64 type using the ParseInt function: num, err := strconv.ParseInt(str, 10, 64)
- Use the ParseFloat function to convert a string to a float64 type: num, err := strconv.ParseFloat(str, 64)
- Handle the conversion results and errors as necessary.
- The conversion was successful, the num variable holds the converted number, and the err variable is nil.
- The conversion failed, the num variable is now 0, and the error variable holds the error message. You can print the error message using fmt.Println(err).
Here is a complete example code:
package main
import (
"fmt"
"strconv"
)
func main() {
str := "12345"
// 字符串转换为int类型
num, err := strconv.Atoi(str)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(num)
}
// 字符串转换为int64类型
num64, err := strconv.ParseInt(str, 10, 64)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(num64)
}
// 字符串转换为float64类型
fnum, err := strconv.ParseFloat(str, 64)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(fnum)
}
}
The output is:
12345
12345
12345
This achieves the function of converting a string into a number.