Home>Article>Backend Development> How to convert integer to string in go language
Conversion method: 1. Use Sprintf() of the fmt package, which supports converting formatted variables into strings, with the syntax "fmt.Sprintf("%d", num)"; 2. Use Itoa of the strconv package (), supports converting the int type into a string, the syntax "strconv.Itoa(num)"; 3. Use FormatInt() of the strconv package, supports converting the int64 type into a string, the syntax "strconv.FormatInt(num,10 )".
The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.
In actual development, we often need to convert some commonly used data types, such as conversion between string, int, int64, float and other data types.
fmt package should be the most common. I have been exposed to it since I first started learning Golang. I have to use it when writing 'hello, world'. It also supports formatting variables into strings. %d represents a decimal integer.
//Sprintf formats according to a format specifier and returns the resulting string. func Sprintf(format string, a ...interface{}) string
Usage example:
str := fmt.Sprintf("%d", a)
in Go language The strconv package provides us with conversion functions between strings and basic data types. Commonly used functions in the strconv package include Atoi(), Itia(), parse series functions, format series functions, append series functions, etc.
The Itoa() function supports the conversion of int type into string
//Itoa is shorthand for FormatInt(int64(i), 10). func Itoa(i int) string
Usage example:
func main() { num := 100 str := strconv.Itoa(num) fmt.Printf("type:%T value:%#v\n", str, str) }
The running result is as follows:
supports int64 type conversion into string
Parameter i is to be The integer to be converted, base is a base, such as base 2, and supports base 2 to base 36.
//FormatInt returns the string representation of i in the given base, for 2 <= base <= 36. The result uses the lower-case letters ‘a' to ‘z' for digit values >= 10. func FormatInt(i int64, base int) string
Usage example:
str := strconv.FormatInt(a, 10)
Common methods
// Atoi returns the result of ParseInt(s, 10, 0) converted to type int. func Atoi(s string) (int, error)
Usage examples:
i,err := strconv.Atoi(a)
Very powerful 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. func ParseInt(s string, base int, bitSize int) (i int64, err error)
Parameter 1 String form of number
Parameter 2 The base of the numeric string, such as binary octal decimal hexadecimal
Parameter 3 The bit size of the returned result is int8 int16 int32 int64
Usage example:
i, err := strconv.ParseInt("123", 10, 32)
[Related recommendations:Go video tutorial,Programming teaching】
The above is the detailed content of How to convert integer to string in go language. For more information, please follow other related articles on the PHP Chinese website!