>

There a lot of situiations that we need do convertions between int and string types of values in Go, here I list the most common convertion function and method that facilitates the operations.

int2string

1、for int32, use strconv.Itoa(i)
2、for int64 or greater, strconv.FormatInt(intValue, 10)

Note: With FormatInt, we must pass an int64 value.

e.g.

1
2
result := strconv.FormatInt(int64(value), 10)
func FormatInt(i int64, base int) string

3、use fmt.Sprintf() for anything

Parsing Custom strings

There is also a handy fmt.Sscanf() which gives even greater flexibility as with the format string you can specify the number format (like width, base etc.) along with additional extra characters in the inputstring.

This is great for parsing custom strings holding a number. For example if your input is provided in a form of “id:00123” where you have a prefix “id:” and the number is fixed 5 digits, padded with zeros if shorter, this is very easily parsable like this:

1
2
3
4
5
s := "id:00123"
var i int
if _, err := fmt.Sscanf(s, "id:%5d", &i); err == nil {
fmt.Println(i)
}

Output: 123

string2int

1
2
flag.Parse()
s := flag.Arg(0)

(1) use strconv.Atoi()

1
2
3
if i, err := strconv.Atoi(s); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}

(2) use strconv.ParseInt()

1
2
3
if i, err := strconv.ParseInt(s, 10, 64); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}

Note:
Argument 2 is the base of the string being parsed. Most numbers we use are base 10.
Argument 3 is the bit size of the resulting int. 0 means int, 6 means int16, with 16 bits.

e.g. 64 tells how many bits of precision to parse

Prototype:

1
func ParseUint(s string, base int, bitSize int) (uint64, error)

also:

1
strconv.ParseFloat()

(3) use fmt.Sscan()

1
2
3
4
var i int
if _, err := fmt.Sscan(s, &i); err == nil {
fmt.Printf("i=%d, type: %T\n", i, i)
}

Output:
i=123, type: int
i=123, type: int64
i=123, type: int

Reference
http://stackoverflow.com/questions/4278430/convert-string-to-integer-type-in-go
https://golang.org/pkg/strconv/#FormatInt