GoGo example

How to convert a string to an int in Go

6 min read▶ Runs in an isolated hosted runtimeUpdated Jul 2026

Quick answer

Use strconv.Atoi: n, err := strconv.Atoi("42"). It returns the int and an error — check the error, because in Go that's the whole conversion story. There is no int("42") cast.

Coming from Python or JavaScript, the surprise is that Go's type conversion syntax doesn't parse: int(s) won't compile for a string, and string(65) gives you "A", not "65". Parsing lives in the strconv package, and every function in it returns (value, error) — which turns out to be exactly what you want, because string-to-int conversion is the canonical place where user input goes wrong. Each example below runs on this page — hit Run, then edit and run it again.

1strconv.AtoiRecommended

strconv.Atoi(s) ("ASCII to integer" — the name is C heritage) parses a plain base-10 integer into an int. It is shorthand for ParseInt(s, 10, 0) and it is the right call for the common case. The error is not optional decoration: anything that isn't exactly an integer — letters, decimals, empty string — comes back as a non-nil err instead of a panic or a silent zero.

atoi.go

Output

Prints 43 — the arithmetic proves it's an int, not a string — then strconv.Atoi: parsing "42abc": invalid syntax. Note the error message quotes the offending input for you, which makes these errors unusually easy to debug in logs.

2ParseInt: bases and bit sizes

strconv.ParseInt(s, base, bitSize) is the general form. base is 2 to 36 (or 0 to auto-detect from a 0x/0b/0o prefix), and bitSize says what the value must fit in — 8, 16, 32, or 64. It always returns an int64; bitSize only controls the range check, so converting down to int8(n) afterwards is safe when you asked for 8. There's a ParseUint twin for unsigned values.

parseint.go

Output

Prints -128, then 255 10, then 255 again from the auto-detected 0x prefix, and finally strconv.ParseInt: parsing "300": value out of range — the string is a perfectly valid integer, it just doesn't fit in 8 bits. With base 16 the 0x prefix must be omitted; only base 0 accepts it.

3Decimal strings: ParseFloat, then convert

Atoi("3.99") fails — a decimal point is a syntax error to an integer parser. If the string can legitimately carry a fraction, parse it as a float first, then decide how it becomes an int: int(f) truncates toward zero, and math.Round rounds to nearest. That's a real decision, not a formality — prices, percentages, and quantities each want a different one.

decimals.go

Output

Prints the invalid syntax error first, then 3 (truncated) and 4 (rounded). Watch negatives: truncation goes toward zero, so int(-3.99) is -3, not -4 — a classic off-by-one in billing code.

4Real-world input: trim, check, keep going

Input from files, prompts, and HTTP forms arrives with whitespace attached — bufio readers in particular hand you the trailing newline, and Atoi("42\n") fails. The fix is a tiny helper that trims first. The same pattern scales to batches: convert each value, skip and report the bad ones, and keep the good ones instead of aborting the lot.

messy.go

Output

Prints 42 <nil>, then skipping "x" -> strconv.Atoi: parsing "x": invalid syntax, then total: 60. strconv.Quote in the log line is a small habit worth copying — it makes invisible characters (the very thing that broke the parse) visible.

5Which should you use?

FunctionReturnsHandlesBest for
strconv.AtoiintBase-10 integersAlmost everything
strconv.ParseIntint64Bases 2–36, bit sizesHex/binary, exact-width ints
strconv.ParseUintuint64Unsigned onlyIDs, sizes, bitmasks
strconv.ParseFloat + int()float64 → intDecimals, exponentsStrings like "3.99"
fmt.SscanfAny via pointersNumbers inside textFixed-format lines

6Pull numbers out of formatted text

When the integer is embedded in a known layout, fmt.Sscanf parses the whole line in one call — it's Scanf reading from a string instead of stdin. You pass a format string and pointers; it fills them and returns how many it matched plus an error. For anything less rigid than a fixed format, split the string or use a regexp and Atoi the pieces instead.

sscanf.go

Output

Prints 24 Jul 2026 — one call parsed two ints and a word. %s stops at whitespace, which is what makes the layout above work; it also means Sscanf is brittle when the format drifts, so keep it for input you control.

7What happens on overflow

Two different things can go wrong in a parse, and Go distinguishes them: ErrSyntax (not a number at all) and ErrRange (a valid number that doesn't fit). On a range error the returned value isn't garbage — it's clamped to the nearest representable value — but you should treat it as unusable unless you've specifically decided saturation is what you want. errors.Is tells the two cases apart.

overflow.go

Output

Prints 9223372036854775807 — the max int64, the clamp in action — then strconv.Atoi: parsing "99999999999999999999": value out of range and true. If values this large are legitimate in your domain, parse into math/big.Int with SetString instead of an int.

Frequently asked questions

Why can’t I convert a string to an int with int("42") in Go?

Go type conversions reinterpret values, they don’t parse text. int(s) on a string doesn’t compile, and the reverse trap is worse: string(rune(65)) gives "A" (the character with that code point), not "65". Parsing text is strconv’s job — strconv.Atoi for string-to-int, strconv.Itoa for int-to-string.

What is the difference between strconv.Atoi and strconv.ParseInt?

Atoi(s) is exactly ParseInt(s, 10, 0) with the result converted to int — base 10 only, sized to the platform int. ParseInt adds a base argument (2 to 36, or 0 to auto-detect a 0x/0b/0o prefix) and a bitSize that range-checks the value, and it always returns an int64. Use Atoi unless you need a specific base or width.

How do I convert a string to an int64 in Go?

Call strconv.ParseInt(s, 10, 64) — it returns an int64 directly. Going through Atoi also works on 64-bit platforms, where int is 64 bits wide, but ParseInt states the width explicitly and behaves identically everywhere, which is what you want in serialization or database code.

How do I tell whether the error was bad input or a number too large?

Check the sentinel with errors.Is: errors.Is(err, strconv.ErrSyntax) means the text wasn’t a number, and errors.Is(err, strconv.ErrRange) means it was a number that doesn’t fit the width you asked for. The error is a *strconv.NumError, which also carries the function name and the input string — that’s why the messages read strconv.Atoi: parsing "x": invalid syntax.

How do I parse a string with thousands separators, like "1,234,567"?

Strip the separators first: strconv.Atoi(strings.ReplaceAll(s, ",", "")) parses "1,234,567" as 1234567. There’s no locale-aware parser in the standard library, so if your input can carry European formats ("1.234.567,89") you need to know the locale and normalize accordingly, or use golang.org/x/text.