#There are many ways to convert strings to numbers in the Go language, and the specific methods depend on the number type to be converted. The following are some common methods:
-
String to integer:
- Use strconv.Atoi(s string) (int, error) function to convert characters Convert string to integer type. This function returns two values, the first value is the converted integer and the second value is the possible error.
- Sample code:
package main import ( "fmt" "strconv" ) func main() { s := "123" i, err := strconv.Atoi(s) if err != nil { fmt.Println("字符串转换为整数失败:", err) return } fmt.Println("字符串转换为整数成功:", i) }
Copy after login -
String to floating point number:
- Use strconv.ParseFloat(s string, bitSize int ) (float64, error) function can convert a string to a floating point number type. This function accepts two parameters, the first parameter is the string to be converted, and the second parameter is the number of digits of the floating point number. This function returns two values, the first value is the converted floating point number, and the second value is the possible error.
- Sample code:
package main import ( "fmt" "strconv" ) func main() { s := "3.1415926" f, err := strconv.ParseFloat(s, 64) if err != nil { fmt.Println("字符串转换为浮点数失败:", err) return } fmt.Println("字符串转换为浮点数成功:", f) }
Copy after login
By using the above method, we can easily convert strings to numeric types. Note that these functions will return an error if the string cannot be converted correctly to a numeric type. Therefore, in practical applications, error handling needs to be carried out according to specific situations.