To convert a Go string to int, call strconv.Atoi(s). It returns the number and an error, and the error is non-nil when the string isn’t a valid whole number. For the other direction, int to string, use strconv.Itoa(n).
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("42")
if err != nil {
fmt.Println("not a number:", err)
return
}
fmt.Println(n + 1)
s := strconv.Itoa(n)
fmt.Println(s + "1")
}Code language: Go (go)
43
421Code language: plaintext (plaintext)
The first line of output is arithmetic (42 + 1), the second is string concatenation (“42” + “1”). The rest of this guide covers every other conversion you’re likely to need: int64, float64, bool, bytes, other number bases, and what to do when the conversion fails.
Quick reference: Go type conversions
Everything that parses a string returns a value and an error. Everything that produces a string always succeeds, so it returns just the string.
| From | To | Use |
|---|---|---|
| string | int | strconv.Atoi(s) |
| string | int64 | strconv.ParseInt(s, 10, 64) |
| string | uint64 | strconv.ParseUint(s, 10, 64) |
| string | float64 | strconv.ParseFloat(s, 64) |
| string | bool | strconv.ParseBool(s) |
| int | string | strconv.Itoa(n) |
| int64 | string | strconv.FormatInt(n, 10) |
| float64 | string | strconv.FormatFloat(f, 'f', -1, 64) |
| bool | string | strconv.FormatBool(b) |
| anything | string | fmt.Sprint(v) or fmt.Sprintf("%v", v) |
| string | []byte | []byte(s) |
| []byte | string | string(b) |
| float64 | int | int(f) (drops the fraction) |
| int | float64 | float64(n) |
Convert a string to an int with strconv.Atoi
Atoi stands for “ASCII to integer”, a name Go inherited from C. It lives in the strconv package of the standard library and parses a string of decimal digits, with an optional + or - in front.
Atoi is strict. The whole string has to be a number, with nothing before or after it. This program shows what passes and what doesn’t:
package main
import (
"fmt"
"strconv"
)
func main() {
inputs := []string{"42", "-42", "+42", "007", " 42", "42abc", "3.14", "1,000", "1_000", "0x2A", ""}
for _, s := range inputs {
n, err := strconv.Atoi(s)
if err != nil {
fmt.Printf("%-8q error: %v\n", s, err)
continue
}
fmt.Printf("%-8q %d\n", s, n)
}
}Code language: Go (go)
"42" 42
"-42" -42
"+42" 42
"007" 7
" 42" error: strconv.Atoi: parsing " 42": invalid syntax
"42abc" error: strconv.Atoi: parsing "42abc": invalid syntax
"3.14" error: strconv.Atoi: parsing "3.14": invalid syntax
"1,000" error: strconv.Atoi: parsing "1,000": invalid syntax
"1_000" error: strconv.Atoi: parsing "1_000": invalid syntax
"0x2A" error: strconv.Atoi: parsing "0x2A": invalid syntax
"" error: strconv.Atoi: parsing "": invalid syntaxCode language: plaintext (plaintext)
A sign and leading zeros are fine. Spaces, letters, a decimal point, thousands separators, a hex prefix and the empty string are all errors. Atoi never returns “the digits it could find”: "42abc" is an error, it doesn’t quietly become 42.
The result is an int, which is 64 bits wide on every 64-bit system. If you need a specific size like int64 or int32, or a base other than 10, use ParseInt (below).
Handle the conversion error
Never throw the error away with n, _ := strconv.Atoi(s). When parsing fails, n is 0, and 0 looks just like a real answer. Check the error first and use the number only when the error is nil. (If the if err != nil pattern is new to you, the errors lesson explains it.)
There are two ways a string can fail to parse, and they produce two different messages:
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.Atoi("abc")
fmt.Println(n, err)
n, err = strconv.Atoi("99999999999999999999")
fmt.Println(n, err)
}Code language: Go (go)
0 strconv.Atoi: parsing "abc": invalid syntax
9223372036854775807 strconv.Atoi: parsing "99999999999999999999": value out of rangeCode language: plaintext (plaintext)
invalid syntaxmeans the string isn’t a number at all. The returned value is 0.value out of rangemeans the string is a number, but it doesn’t fit in the type. The returned value is the largest (or, for negative numbers, the smallest) value that does fit. That’s still wrong, so treat it as a failure.
Tell the two errors apart with errors.Is
Often one check is enough: if err != nil, tell the user the input is invalid. When you want a different message for each case, compare against strconv.ErrSyntax and strconv.ErrRange with errors.Is:
package main
import (
"errors"
"fmt"
"strconv"
)
func parseQuantity(s string) (int, error) {
n, err := strconv.Atoi(s)
switch {
case errors.Is(err, strconv.ErrSyntax):
return 0, fmt.Errorf("%q is not a whole number", s)
case errors.Is(err, strconv.ErrRange):
return 0, fmt.Errorf("%q is too large", s)
case err != nil:
return 0, err
}
return n, nil
}
func main() {
for _, s := range []string{"12", "twelve", "12000000000000000000"} {
n, err := parseQuantity(s)
if err != nil {
fmt.Println("error:", err)
continue
}
fmt.Println("quantity:", n)
}
}Code language: Go (go)
quantity: 12
error: "twelve" is not a whole number
error: "12000000000000000000" is too largeCode language: plaintext (plaintext)
You need errors.Is here because a plain err == strconv.ErrSyntax is always false. The error that strconv returns is a *strconv.NumError that wraps ErrSyntax or ErrRange and adds the function name and the input. You can get at those fields too:
package main
import (
"errors"
"fmt"
"strconv"
)
func main() {
_, err := strconv.Atoi("abc")
fmt.Println(err == strconv.ErrSyntax)
fmt.Println(errors.Is(err, strconv.ErrSyntax))
if numErr, ok := errors.AsType[*strconv.NumError](err); ok {
fmt.Println("Func:", numErr.Func)
fmt.Println("Num: ", numErr.Num)
fmt.Println("Err: ", numErr.Err)
}
}Code language: Go (go)
false
true
Func: Atoi
Num: abc
Err: invalid syntaxCode language: plaintext (plaintext)
All the parsing functions in strconv report errors this way. Only the function name in the message changes: strconv.ParseInt: parsing ..., strconv.ParseFloat: parsing ... and so on.
Trim whitespace before parsing input
The most common cause of invalid syntax on a string that looks fine is invisible whitespace. A line read from the keyboard or a file with ReadString('\n') still has its newline at the end, and the error message shows it if you look closely:
package main
import (
"bufio"
"fmt"
"strconv"
"strings"
)
func main() {
// Stands in for os.Stdin: the user typed 42 and pressed Enter.
reader := bufio.NewReader(strings.NewReader("42\n"))
line, _ := reader.ReadString('\n')
_, err := strconv.Atoi(line)
fmt.Println(err)
n, err := strconv.Atoi(strings.TrimSpace(line))
fmt.Println(n, err)
}Code language: Go (go)
strconv.Atoi: parsing "42\n": invalid syntax
42 <nil>Code language: plaintext (plaintext)
strings.TrimSpace removes spaces, tabs and line endings (including the \r\n that Windows uses) from both ends of a string. Call it on anything that comes from a person, a file or a form before you parse it. A bufio.Scanner strips the line ending for you, but not spaces around the number, so trimming is still a good habit there. The files lesson covers reading input line by line.
Convert a string to int64 with strconv.ParseInt
strconv.ParseInt is the general version of Atoi. It takes two extra arguments, the base and the bit size, and always returns an int64:
n, err := strconv.ParseInt(s, 10, 64) // string, base, bit sizeCode language: Go (go)
strconv.Atoi(s) does the same as strconv.ParseInt(s, 10, 0) with the result converted to int.
The base: binary, octal and hex strings
The base can be anything from 2 to 36. Base 10 is decimal, 16 is hexadecimal, 2 is binary. With an explicit base, the string must contain only digits of that base, without a prefix. Base 0 is special: it tells ParseInt to work out the base from the prefix, the same way Go reads numbers in source code.
package main
import (
"fmt"
"strconv"
)
func main() {
tests := []struct {
s string
base int
}{
{"255", 10},
{"ff", 16},
{"FF", 16},
{"11111111", 2},
{"0xff", 16},
{"0xff", 0},
{"0b11111111", 0},
{"0o377", 0},
{"1_000_000", 0},
}
for _, t := range tests {
n, err := strconv.ParseInt(t.s, t.base, 64)
if err != nil {
fmt.Printf("%-12q base %-2d error: %v\n", t.s, t.base, err)
continue
}
fmt.Printf("%-12q base %-2d %d\n", t.s, t.base, n)
}
}Code language: Go (go)
"255" base 10 255
"ff" base 16 255
"FF" base 16 255
"11111111" base 2 255
"0xff" base 16 error: strconv.ParseInt: parsing "0xff": invalid syntax
"0xff" base 0 255
"0b11111111" base 0 255
"0o377" base 0 255
"1_000_000" base 0 1000000Code language: plaintext (plaintext)
Note the fifth line: "0xff" with base 16 fails, because the 0x prefix is only understood with base 0. Base 0 also allows underscores between digits. Be careful with base 0 on user input, though: a leading zero means octal there, so "017" parses as 15.
The bit size: int8, int16, int32 or int64
The bit size (0, 8, 16, 32 or 64) says which integer type the result has to fit in. Size 0 means int. The return type stays int64 whatever you pass. What changes is the range check: if the number doesn’t fit in the size you asked for, you get value out of range.
package main
import (
"fmt"
"strconv"
)
func main() {
n, err := strconv.ParseInt("300", 10, 8)
fmt.Println(n, err)
n, err = strconv.ParseInt("300", 10, 32)
if err != nil {
fmt.Println(err)
return
}
small := int32(n) // safe: ParseInt checked that it fits
fmt.Printf("%d is a %T, %d is a %T\n", n, n, small, small)
}Code language: Go (go)
127 strconv.ParseInt: parsing "300": value out of range
300 is a int64, 300 is a int32Code language: plaintext (plaintext)
An int8 holds -128 to 127, so 300 is out of range and you get the nearest value that fits, plus the error. This is why the bit size matters: parse with the size of the type you’re going to store the number in, and the conversion afterwards can’t silently cut off bits.
For unsigned types there’s strconv.ParseUint, with the same arguments and a uint64 result. It rejects any sign, so strconv.ParseUint("-1", 10, 64) fails with invalid syntax.
Convert an int to a string with strconv.Itoa
The usual golang idiom for int to string is strconv.Itoa(n) (“integer to ASCII”). It can’t fail, so there’s no error to check. You need it whenever you glue a number to a string with +, because Go doesn’t convert between the two on its own:
package main
import "fmt"
func main() {
fmt.Println("Age: " + 42)
}Code language: Go (go)
./main.go:6:14: invalid operation: "Age: " + 42 (mismatched types untyped string and untyped int)Code language: plaintext (plaintext)
With Itoa it works:
package main
import (
"fmt"
"strconv"
)
func main() {
age := 42
fmt.Println("Age: " + strconv.Itoa(age))
}Code language: Go (go)
Age: 42Code language: plaintext (plaintext)
Why string(65) gives “A” and not “65”
If you come from another language, string(n) looks like the obvious way to turn an int into a string. In Go it compiles, but it does something else: it treats the number as a Unicode code point and gives you that one character. Code point 65 is the letter A, so string(65) is "A".
Because this is almost never what people mean, go vet reports it. Here’s the program and what go vet says about it:
package main
import "fmt"
func main() {
n := 65
fmt.Println(string(n))
}Code language: Go (go)
main.go:7:14: conversion from int to string yields a string of one rune, not a string of digitsCode language: plaintext (plaintext)
go build and go run accept this program and it prints A. But go test runs this vet check automatically and refuses to run your tests until you fix it, and most editors underline it. The fix depends on what you meant:
package main
import (
"fmt"
"strconv"
)
func main() {
n := 65
fmt.Println(strconv.Itoa(n)) // the digits
fmt.Println(string(rune(n))) // the character
}Code language: Go (go)
65
ACode language: plaintext (plaintext)
Converting through rune tells both the reader and go vet that you really want the character. Runes are explained in the strings lesson.
Convert an int64 to a string with strconv.FormatInt
Itoa takes an int. For an int64, or for output in another base, use strconv.FormatInt(n, base). FormatUint does the same for uint64. Neither adds a prefix like 0x.
package main
import (
"fmt"
"strconv"
)
func main() {
var id int64 = 255
fmt.Println(strconv.FormatInt(id, 10))
fmt.Println(strconv.FormatInt(id, 2))
fmt.Println(strconv.FormatInt(id, 16))
fmt.Println(strconv.FormatInt(-id, 16))
fmt.Println(strconv.FormatUint(uint64(id), 8))
var small int32 = 7
fmt.Println(strconv.Itoa(int(small)))
}Code language: Go (go)
255
11111111
ff
-ff
377
7Code language: plaintext (plaintext)
For the smaller integer types such as int32 or uint8, convert to int or int64 first, as in the last line. That conversion is always safe because the bigger type can hold every value of the smaller one.
Convert a string to float64 with strconv.ParseFloat
strconv.ParseFloat(s, 64) parses a decimal number into a float64. It accepts a decimal point, an exponent, and the special values inf, infinity and nan in any mix of upper and lower case.
package main
import (
"fmt"
"strconv"
)
func main() {
for _, s := range []string{"3.14", "42", "-0.5", ".5", "1e3", "NaN", "3,14", "$3.14", "1e400"} {
f, err := strconv.ParseFloat(s, 64)
if err != nil {
fmt.Printf("%-7q error: %v\n", s, err)
continue
}
fmt.Printf("%-7q %v\n", s, f)
}
}Code language: Go (go)
"3.14" 3.14
"42" 42
"-0.5" -0.5
".5" 0.5
"1e3" 1000
"NaN" NaN
"3,14" error: strconv.ParseFloat: parsing "3,14": invalid syntax
"$3.14" error: strconv.ParseFloat: parsing "$3.14": invalid syntax
"1e400" error: strconv.ParseFloat: parsing "1e400": value out of rangeCode language: plaintext (plaintext)
Two things to watch for. The decimal separator is always a point, so "3,14" as written in much of Europe is an error. And a number that’s too large for a float64, like 1e400, gives value out of range with infinity as the returned value.
The second argument is the bit size, 32 or 64. Like ParseInt, ParseFloat always returns the widest type, a float64. With 32 you get a value that converts to float32 without changing: float32(f).
Convert a float to a string with strconv.FormatFloat
FormatFloat has four arguments: the number, a format, a precision and the bit size of the original type (64 for a float64).
- The format is a single character:
'f'for plain decimals (1234.5678),'e'for scientific notation (1.2345678e+03), and'g'to use'e'for very large or very small numbers and'f'otherwise. - The precision is the number of digits after the decimal point for
'f'and'e'. The special precision -1 means “as few digits as needed to get the exact same number back when parsing”.
package main
import (
"fmt"
"strconv"
)
func main() {
f := 1234.5678
fmt.Println(strconv.FormatFloat(f, 'f', -1, 64))
fmt.Println(strconv.FormatFloat(f, 'f', 2, 64))
fmt.Println(strconv.FormatFloat(f, 'f', 0, 64))
fmt.Println(strconv.FormatFloat(f, 'e', -1, 64))
fmt.Println(strconv.FormatFloat(f, 'e', 2, 64))
fmt.Println(strconv.FormatFloat(100, 'f', -1, 64))
fmt.Println(strconv.FormatFloat(1e21, 'g', -1, 64))
}Code language: Go (go)
1234.5678
1234.57
1235
1.2345678e+03
1.23e+03
100
1e+21Code language: plaintext (plaintext)
A fixed precision rounds, it doesn’t cut off: 1234.5678 becomes 1234.57 with two decimals. Use 'f' with -1 when a program will read the string back, and a fixed precision like 2 when a person will read it. The Go Printf guide shows how to do that with %.2f.
Convert a string to a bool with strconv.ParseBool
strconv.ParseBool accepts a fixed list of spellings: 1, t, T, true, TRUE and True for true, and 0, f, F, false, FALSE and False for false. Everything else is an error, including yes, on and mixed case like tRUE.
package main
import (
"fmt"
"strconv"
)
func main() {
for _, s := range []string{"true", "T", "1", "False", "0", "yes", "tRUE"} {
b, err := strconv.ParseBool(s)
fmt.Println(b, err)
}
fmt.Println(strconv.FormatBool(true) + "!")
}Code language: Go (go)
true <nil>
true <nil>
true <nil>
false <nil>
false <nil>
false strconv.ParseBool: parsing "yes": invalid syntax
false strconv.ParseBool: parsing "tRUE": invalid syntax
true!Code language: plaintext (plaintext)
If your input uses other words, such as “yes” and “no” from a form, lowercase it with strings.ToLower and compare it yourself with a switch. strconv.FormatBool goes the other way and returns "true" or "false".
Convert a float to an int (truncation)
Between number types you don’t need a package. A conversion is written as the type name with the value in parentheses: int(f), float64(n). Converting a float to an int drops everything after the decimal point. It doesn’t round.
package main
import (
"fmt"
"math"
)
func main() {
price := 3.99
loss := -3.99
fmt.Println(int(price), int(loss))
fmt.Println(int(math.Round(price)), int(math.Round(loss)))
fmt.Println(int(math.Floor(price)), int(math.Floor(loss)))
fmt.Println(int(math.Ceil(price)), int(math.Ceil(loss)))
a, b := 7, 2
fmt.Println(a/b, float64(a)/float64(b))
}Code language: Go (go)
3 -3
4 -4
3 -4
4 -3
3 3.5Code language: plaintext (plaintext)
Truncation goes toward zero, so 3.99 becomes 3 and -3.99 becomes -3. To round to the nearest whole number, call math.Round first. math.Floor always rounds down and math.Ceil always rounds up. The last line shows the conversion in the other direction: dividing two ints gives an int (7/2 is 3), so convert to float64 before dividing when you want 3.5.
Check the range yourself before converting a float that might be huge, or NaN. If the value doesn’t fit in the integer type, the conversion still “succeeds”, but the Go spec leaves the result up to the implementation, and it differs between processor types.
This only applies to variables. A float constant with a fraction can’t be converted at all, the compiler stops you:
package main
import "fmt"
func main() {
fmt.Println(int(3.99))
}Code language: Go (go)
./main.go:6:18: cannot convert 3.99 (untyped float constant) to type intCode language: plaintext (plaintext)
To go from a string holding a decimal number to an int, combine the two steps: ParseFloat first, then int(f) or int(math.Round(f)). strconv.Atoi("3.99") is an error, as you saw at the start.
Convert a string to []byte and back
A string is a read-only sequence of bytes, and a lot of the standard library (files, network connections, hashing) works with []byte. Converting between the two is a plain conversion that can’t fail:
package main
import "fmt"
func main() {
s := "héllo"
b := []byte(s)
fmt.Println(b, len(b))
b[0] = 'H'
fmt.Println(string(b), s)
r := []rune(s)
fmt.Println(r, len(r), string(r))
}Code language: Go (go)
[104 195 169 108 108 111] 6
Héllo héllo
[104 233 108 108 111] 5 hélloCode language: plaintext (plaintext)
[]byte(s) makes a copy, so changing the slice leaves the original string alone, and string(b) copies again on the way back. The slice has 6 bytes for 5 characters because é takes two bytes in UTF-8. When you need to work with characters instead of bytes, convert to []rune, which gives one element per character.
Printing a byte slice with fmt.Println shows the numbers, as above. That often confuses people who read a file and see a list of numbers: wrap it in string(...) to see the text.
fmt.Sprint and fmt.Sprintf, or strconv?
The fmt package can turn any value into a string too. fmt.Sprint(v) uses the default format for the value, and fmt.Sprintf takes a format string with verbs like %d and %.2f:
package main
import "fmt"
func main() {
s := fmt.Sprint(42)
fmt.Println(s + "!")
fmt.Println(fmt.Sprint(3.5), fmt.Sprint(true), fmt.Sprint(int64(7)))
fmt.Println(fmt.Sprintf("%d items at $%.2f", 3, 4.5))
fmt.Println(fmt.Sprintf("%05d|%x|%b", 42, 42, 42))
}Code language: Go (go)
42!
3.5 true 7
3 items at $4.50
00042|2a|101010Code language: plaintext (plaintext)
Here’s how I choose between them:
- To convert one number, I use
strconv. It says exactly what happens, the compiler checks the argument type, and it’s faster becausefmthas to inspect the value’s type while the program runs. You’ll only notice the difference in a loop that runs millions of times. - To build a sentence out of several values, or when I need padding, a fixed number of decimals or alignment, I use
fmt.Sprintf. One format string is easier to read than a chain of+andstrconvcalls. - To parse a string into a number, I always use
strconv.fmthas scanning functions likefmt.Sscan, but they are slower and more forgiving:fmt.Sscan("42abc", &n)happily stores 42 and reports no error.
Key takeaways
- String to int is
strconv.Atoi(s), int to string isstrconv.Itoa(n).string(n)gives a character, not the digits. - Always check the error from a parsing function.
invalid syntaxmeans it isn’t a number,value out of rangemeans it doesn’t fit. Useerrors.Iswithstrconv.ErrSyntaxandstrconv.ErrRangeto tell them apart. - Call
strings.TrimSpaceon input before parsing it. A stray newline or space is an error. ParseInt(s, base, bitSize)andParseFloat(s, bitSize)handle int64, other sizes and other bases. They returnint64andfloat64, and the bit size only sets the range check.int(f)truncates toward zero. Usemath.Roundfirst if you want rounding.- Use
strconvfor single conversions and all parsing, andfmt.Sprintfwhen you’re formatting several values into one string.