The article directories

1. Int Integer to string 1.1fmt.Sprintf 1.2strconv.Itoa 1.3strconv.FormatInt

2. String to int 2.1 strconv.atoi 2.2 strconv.parseint


1. Convert an int to a string

1.1 FMT. Sprintf

The FMT package is probably the most common. It’s been around since the beginning of Golang, so you need it to write ‘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
Copy the code

Example:

str := fmt.Sprintf("%d", a)
Copy the code


1.2 strconv.Itoa

Support int type conversion to string

//Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string
Copy the code

Example:

str := strconv.Itoa(a)
Copy the code


1.3 strconv.FormatInt

Support int64 type conversion to string the argument I is the integer to be converted, base is base, such as base 2, support 2 to 36 base.

//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 values >= 10.
func FormatInt(i int64, base int) string
Copy the code

Example:

str := strconv.FormatInt(a, 10)
Copy the code

2. The string is converted to an int

2.1 strconv.Atoi

More common methods

// Atoi returns the result of ParseInt(s, 10, 0) converted to type int.
func Atoi(s string) (int, error)
Copy the code

Example:

i,err := strconv.Atoi(a)
Copy the code


2.2 strconv.ParseInt

Very powerful

// 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)
Copy the code

Parameter 1 Is a string of digits. Parameter 2 Is a string of digits. For example, binary octal decimal hexadecimal parameter 3 Is the bit size of the result, int8 int16 int32 int64

Example:

i, err := strconv.ParseInt("123".10.32)
Copy the code