Home > Article > Backend Development > In-depth analysis of the conversion method between strings and numbers in Golang
In Golang, conversion between strings and numbers is a very common operation. This article will introduce in detail the mutual conversion method between strings and numbers in Golang, and provide specific code examples.
1. Convert strings to numbers
In Golang, there are the following methods to convert strings to numbers:
The Atoi() function can convert a string into a number of type int. The sample code is as follows:
package main import ( "fmt" "strconv" ) func main() { str := "123" num, err := strconv.Atoi(str) if err != nil { fmt.Println("字符串转换为数字失败") } else { fmt.Printf("转换后的数字是%d,类型是%T", num, num) } }
Running results:
转换后的数字是123,类型是int
The ParseInt() function can convert the string It is an arbitrary number. The sample code is as follows:
package main import ( "fmt" "strconv" ) func main() { str := "101" num, err := strconv.ParseInt(str, 2, 0) if err != nil { fmt.Println("字符串转换为数字失败") } else { fmt.Printf("转换后的数字是%d,类型是%T", num, num) } }
Running results:
转换后的数字是5,类型是int64
The Scanf() function can convert the input characters Convert string to number. The sample code is as follows:
package main import ( "fmt" ) func main() { var num int fmt.Printf("请输入一个数字:") _, err := fmt.Scanf("%d", &num) if err != nil { fmt.Println("输入错误") } else { fmt.Printf("转换后的数字是%d,类型是%T", num, num) } }
Running results:
请输入一个数字:123 转换后的数字是123,类型是int
2. Convert numbers to strings
In Golang, there are the following methods to convert numbers to strings :
The Itoa() function can convert int type numbers to strings. The sample code is as follows:
package main import ( "fmt" "strconv" ) func main() { num := 123 str := strconv.Itoa(num) fmt.Printf("转换后的字符串是%s,类型是%T", str, str) }
Running results:
转换后的字符串是123,类型是string
The Sprintf() function can convert any type of Convert data to string. The sample code is as follows:
package main import ( "fmt" ) func main() { num := 123 str := fmt.Sprintf("%d", num) fmt.Printf("转换后的字符串是%s,类型是%T", str, str) }
Running results:
转换后的字符串是123,类型是string
The FormatInt() function can convert any base number into Convert the number to a string. The sample code is as follows:
package main import ( "fmt" "strconv" ) func main() { num := 5 str := strconv.FormatInt(int64(num), 2) fmt.Printf("转换后的字符串是%s,类型是%T", str, str) }
Running results:
转换后的字符串是101,类型是string
Summary:
The above is a detailed explanation of the mutual conversion method between strings and numbers in Golang, and provides specific code examples . In actual development, choosing an appropriate method for conversion can improve the efficiency of the code. At the same time, attention should be paid to errors that may occur during the conversion process.
The above is the detailed content of In-depth analysis of the conversion method between strings and numbers in Golang. For more information, please follow other related articles on the PHP Chinese website!