Go Reference ยท strings and strconv
Go strconv.Atoi() function
Reference for Go strconv.Atoi: convert a decimal string to an int, handle syntax and range errors, and know what whitespace and signs are accepted.
strconv.Atoi ("ASCII to integer") parses a decimal string and returns an int. It is the everyday way to turn text such as a command-line argument, a query-string value or a line from a file into a number.
It accepts an optional leading + or - followed by decimal digits, and nothing else. If the text is anything different, you get an error you must handle.
n, err := strconv.Atoi("-17") if err != nil { // handle bad input }
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 Atoi(s string) (int, error)
| Name | Description |
|---|---|
s |
A decimal integer with an optional sign. No spaces, no prefixes like 0x, no underscores, no decimal point. |
Returns: the value as an int and a nil error on success.
Errors: a *strconv.NumError wrapping strconv.ErrSyntax when s is empty or malformed, or strconv.ErrRange when the value does not fit in an int. After a range error the returned value is the largest or smallest int; after a syntax error it is 0.
Usage notes
intis platform sized. On 64-bit systems it holds 64 bits; on 32-bit systems it holds 32. For a fixed width useParseIntwith a bit size.- Leading zeros are fine and are not octal:
"007"is 7. - Trim first. User input often has spaces or a newline; call
strings.TrimSpace(s)before converting. - Other bases need
ParseInt."0x10"and"1_000"fail here becauseAtoiis fixed to base 10 (ParseInt(s, 0, 64)accepts both). - Floats are rejected.
Atoi("3.5")is a syntax error; useParseFloatand then convert. - Equivalent to
ParseInt(s, 10, 0)converted toint, with a fast path for short strings. - Do not discard the error with
_: a failed parse silently becomes0, which can mask bugs such as division by zero later on.