Go Reference ยท strings and strconv
Go strconv package
Overview of Go's strconv package: convert strings to numbers and booleans, format numbers as text, quote strings, and handle NumError, ErrSyntax and ErrRange.
The strconv package converts between strings and basic types. Go never converts types implicitly, and string(65) gives "A", not "65", so any time you read a number from a file, a form field, a command-line flag or JSON text, or print one in a specific format, strconv is the tool.
Its functions fall into four families: parse (Atoi, ParseInt, ParseUint, ParseFloat, ParseBool), format (Itoa, FormatInt, FormatFloat, FormatBool), append variants that write into an existing []byte (AppendInt, AppendQuote, ...), and quote functions (Quote, Unquote).
import "strconv" n, err := strconv.Atoi("42") s := strconv.Itoa(n + 1)
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.
What the package contains
| Function | Purpose |
|---|---|
Atoi / Itoa |
Decimal int to and from string. |
ParseInt, ParseUint, ParseFloat, ParseBool |
Parse with a base and a bit size. |
FormatInt, FormatUint, FormatFloat, FormatBool |
Format numbers in any base or float layout. |
Quote, QuoteToASCII, QuoteRune, Unquote |
Go-syntax string literals. |
AppendInt, AppendFloat, AppendBool, AppendQuote |
Like the Format functions but append to a []byte, avoiding a string allocation. |
Errors: parse functions return a *strconv.NumError holding the function name (Func), the input (Num) and the cause (Err), which is either strconv.ErrSyntax or strconv.ErrRange. Use errors.Is to test the cause.
Usage notes
- Never ignore the error from a parse function. On failure the numeric result is
0(or the nearest limit for range errors), which looks like valid data. - No whitespace trimming.
Atoi(" 5")fails. Callstrings.TrimSpacefirst when input comes from users. string(n)is not conversion. Converting an integer tostringyields the character with that code point;go vetwarns about it. UseItoa.fmt.Sprint(n)also works but is slower and less explicit; usestrconvin hot paths.- Locale-free.
strconvalways uses.as the decimal point and never adds thousands separators. - Append variants are useful in tight loops: reuse one buffer with
buf = strconv.AppendInt(buf[:0], n, 10).