Go Reference ยท strings and strconv
Go strconv.Itoa() function
Reference for Go strconv.Itoa: convert an int to its decimal string, avoid the string(int) mistake, and compare it with fmt.Sprint, FormatInt and AppendInt.
strconv.Itoa ("integer to ASCII") returns the decimal text of an int. It is the standard way to put a number into a string: building a file name, a cache key or an ID.
A very common beginner mistake is string(65), which does not give "65": it gives "A", the character with code point 65. Itoa is the correct tool when you want the digits.
s := strconv.Itoa(2026) // "2026"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.
Syntax
func Itoa(i int) string
| Name | Description |
|---|---|
i |
The integer to convert. Any int value, including negative numbers. |
Returns: the base-10 representation with a leading - for negative values and no padding, grouping or plus sign. It cannot fail.
Usage notes
string(n)is a bug for numbers. For an integern,string(n)converts a code point to a UTF-8 string.go vetreports it ("conversion from int to string yields a string of one rune").- It is exactly
FormatInt(int64(i), 10), with a fast path for small values (0 to 99 return preconstructed strings with no allocation). - Other integer types need a cast.
Itoatakesint, so usestrconv.Itoa(int(x))orFormatIntforint64,uint64and other bases. - Faster than
fmt.Sprint.fmtuses reflection-like machinery and allocates more; preferItoain hot paths andfmtwhen mixing several values. - No formatting options. For padding (
%05d), thousands separators or signs, usefmt.Sprintf. - Concatenation in loops: combine with
strings.Builderinstead of+=.