version: 1.10

package strconv

import "strconv"

Overview

Package strconv implements conversions to and from string representations of
basic data types.

Numeric Conversions

The most common numeric conversions are Atoi (string to int) and Itoa (int to
string).

  1. i, err := strconv.Atoi("-42")
  2. s := strconv.Itoa(-42)

These assume decimal and the Go int type.

ParseBool, ParseFloat, ParseInt, and ParseUint convert strings to values:

  1. b, err := strconv.ParseBool("true")
  2. f, err := strconv.ParseFloat("3.1415", 64)
  3. i, err := strconv.ParseInt("-42", 10, 64)
  4. u, err := strconv.ParseUint("42", 10, 64)

The parse functions return the widest type (float64, int64, and uint64), but if
the size argument specifies a narrower width the result can be converted to that
narrower type without data loss:

  1. s := "2147483647" // biggest int32
  2. i64, err := strconv.ParseInt(s, 10, 32)
  3. ...
  4. i := int32(i64)

FormatBool, FormatFloat, FormatInt, and FormatUint convert values to strings:

  1. s := strconv.FormatBool(true)
  2. s := strconv.FormatFloat(3.1415, 'E', -1, 64)
  3. s := strconv.FormatInt(-42, 16)
  4. s := strconv.FormatUint(42, 16)

AppendBool, AppendFloat, AppendInt, and AppendUint are similar but append the
formatted value to a destination slice.

String Conversions

Quote and QuoteToASCII convert strings to quoted Go string literals. The latter
guarantees that the result is an ASCII string, by escaping any non-ASCII Unicode
with \u:

  1. q := Quote("Hello, 世界")
  2. q := QuoteToASCII("Hello, 世界")

QuoteRune and QuoteRuneToASCII are similar but accept runes and return quoted Go
rune literals.

Unquote and UnquoteChar unquote Go string and rune literals.

Index

Examples

Package files

atob.go atof.go atoi.go decimal.go doc.go extfloat.go ftoa.go isprint.go itoa.go quote.go

Constants

  1. const IntSize = intSize

IntSize is the size in bits of an int or uint value.

Variables

  1. var ErrRange = errors.New("value out of range")

ErrRange indicates that a value is out of range for the target type.

  1. var ErrSyntax = errors.New("invalid syntax")

ErrSyntax indicates that a value does not have the right syntax for the target
type.

func AppendBool

  1. func AppendBool(dst []byte, b bool) []byte

AppendBool appends “true” or “false”, according to the value of b, to dst and
returns the extended buffer.


Example:

  1. b := []byte("bool:")
  2. b = strconv.AppendBool(b, true)
  3. fmt.Println(string(b))
  4. // Output:
  5. // bool:true

func AppendFloat

  1. func AppendFloat(dst []byte, f float64, fmt byte, prec, bitSize int) []byte

AppendFloat appends the string form of the floating-point number f, as generated
by FormatFloat, to dst and returns the extended buffer.


Example:

  1. b32 := []byte("float32:")
  2. b32 = strconv.AppendFloat(b32, 3.1415926535, 'E', -1, 32)
  3. fmt.Println(string(b32))
  4. b64 := []byte("float64:")
  5. b64 = strconv.AppendFloat(b64, 3.1415926535, 'E', -1, 64)
  6. fmt.Println(string(b64))
  7. // Output:
  8. // float32:3.1415927E+00
  9. // float64:3.1415926535E+00

func AppendInt

  1. func AppendInt(dst []byte, i int64, base int) []byte

AppendInt appends the string form of the integer i, as generated by FormatInt,
to dst and returns the extended buffer.


Example:

  1. b10 := []byte("int (base 10):")
  2. b10 = strconv.AppendInt(b10, -42, 10)
  3. fmt.Println(string(b10))
  4. b16 := []byte("int (base 16):")
  5. b16 = strconv.AppendInt(b16, -42, 16)
  6. fmt.Println(string(b16))
  7. // Output:
  8. // int (base 10):-42
  9. // int (base 16):-2a

func AppendQuote

  1. func AppendQuote(dst []byte, s string) []byte

AppendQuote appends a double-quoted Go string literal representing s, as
generated by Quote, to dst and returns the extended buffer.


Example:

  1. b := []byte("quote:")
  2. b = strconv.AppendQuote(b, `"Fran & Freddie's Diner"`)
  3. fmt.Println(string(b))
  4. // Output:
  5. // quote:"\"Fran & Freddie's Diner\""

func AppendQuoteRune

  1. func AppendQuoteRune(dst []byte, r rune) []byte

AppendQuoteRune appends a single-quoted Go character literal representing the
rune, as generated by QuoteRune, to dst and returns the extended buffer.


Example:

  1. b := []byte("rune:")
  2. b = strconv.AppendQuoteRune(b, '☺')
  3. fmt.Println(string(b))
  4. // Output:
  5. // rune:'☺'

func AppendQuoteRuneToASCII

  1. func AppendQuoteRuneToASCII(dst []byte, r rune) []byte

AppendQuoteRuneToASCII appends a single-quoted Go character literal representing
the rune, as generated by QuoteRuneToASCII, to dst and returns the extended
buffer.


Example:

  1. b := []byte("rune (ascii):")
  2. b = strconv.AppendQuoteRuneToASCII(b, '☺')
  3. fmt.Println(string(b))
  4. // Output:
  5. // rune (ascii):'\u263a'

func AppendQuoteRuneToGraphic

  1. func AppendQuoteRuneToGraphic(dst []byte, r rune) []byte

AppendQuoteRuneToGraphic appends a single-quoted Go character literal
representing the rune, as generated by QuoteRuneToGraphic, to dst and returns
the extended buffer.

func AppendQuoteToASCII

  1. func AppendQuoteToASCII(dst []byte, s string) []byte

AppendQuoteToASCII appends a double-quoted Go string literal representing s, as
generated by QuoteToASCII, to dst and returns the extended buffer.


Example:

  1. b := []byte("quote (ascii):")
  2. b = strconv.AppendQuoteToASCII(b, `"Fran & Freddie's Diner"`)
  3. fmt.Println(string(b))
  4. // Output:
  5. // quote (ascii):"\"Fran & Freddie's Diner\""

func AppendQuoteToGraphic

  1. func AppendQuoteToGraphic(dst []byte, s string) []byte

AppendQuoteToGraphic appends a double-quoted Go string literal representing s,
as generated by QuoteToGraphic, to dst and returns the extended buffer.

func AppendUint

  1. func AppendUint(dst []byte, i uint64, base int) []byte

AppendUint appends the string form of the unsigned integer i, as generated by
FormatUint, to dst and returns the extended buffer.


Example:

  1. b10 := []byte("uint (base 10):")
  2. b10 = strconv.AppendUint(b10, 42, 10)
  3. fmt.Println(string(b10))
  4. b16 := []byte("uint (base 16):")
  5. b16 = strconv.AppendUint(b16, 42, 16)
  6. fmt.Println(string(b16))
  7. // Output:
  8. // uint (base 10):42
  9. // uint (base 16):2a

func Atoi

  1. func Atoi(s string) (int, error)

Atoi returns the result of ParseInt(s, 10, 0) converted to type int.


Example:

  1. v := "10"
  2. if s, err := strconv.Atoi(v); err == nil {
  3. fmt.Printf("%T, %v", s, s)
  4. }
  5. // Output:
  6. // int, 10

func CanBackquote

  1. func CanBackquote(s string) bool

CanBackquote reports whether the string s can be represented unchanged as a
single-line backquoted string without control characters other than tab.


Example:

  1. fmt.Println(strconv.CanBackquote("Fran & Freddie's Diner ☺"))
  2. fmt.Println(strconv.CanBackquote("`can't backquote this`"))
  3. // Output:
  4. // true
  5. // false

func FormatBool

  1. func FormatBool(b bool) string

FormatBool returns “true” or “false” according to the value of b


Example:

  1. v := true
  2. s := strconv.FormatBool(v)
  3. fmt.Printf("%T, %v\n", s, s)
  4. // Output:
  5. // string, true

func FormatFloat

  1. func FormatFloat(f float64, fmt byte, prec, bitSize int) string

FormatFloat converts the floating-point number f to a string, according to the
format fmt and precision prec. It rounds the result assuming that the original
was obtained from a floating-point value of bitSize bits (32 for float32, 64 for
float64).

The format fmt is one of ‘b’ (-ddddp±ddd, a binary exponent), ‘e’ (-d.dddde±dd,
a decimal exponent), ‘E’ (-d.ddddE±dd, a decimal exponent), ‘f’ (-ddd.dddd, no
exponent), ‘g’ (‘e’ for large exponents, ‘f’ otherwise), or ‘G’ (‘E’ for large
exponents, ‘f’ otherwise).

The precision prec controls the number of digits (excluding the exponent)
printed by the ‘e’, ‘E’, ‘f’, ‘g’, and ‘G’ formats. For ‘e’, ‘E’, and ‘f’ it is
the number of digits after the decimal point. For ‘g’ and ‘G’ it is the total
number of digits. The special precision -1 uses the smallest number of digits
necessary such that ParseFloat will return f exactly.


Example:

  1. v := 3.1415926535
  2. s32 := strconv.FormatFloat(v, 'E', -1, 32)
  3. fmt.Printf("%T, %v\n", s32, s32)
  4. s64 := strconv.FormatFloat(v, 'E', -1, 64)
  5. fmt.Printf("%T, %v\n", s64, s64)
  6. // Output:
  7. // string, 3.1415927E+00
  8. // string, 3.1415926535E+00

func FormatInt

  1. func FormatInt(i int64, base int) string

FormatInt returns the string representation of i in the given base, for 2 <=
base <= 36. The result uses the lower-case letters ‘a’ to ‘z’ for digit values

= 10.


Example:

  1. v := int64(-42)
  2. s10 := strconv.FormatInt(v, 10)
  3. fmt.Printf("%T, %v\n", s10, s10)
  4. s16 := strconv.FormatInt(v, 16)
  5. fmt.Printf("%T, %v\n", s16, s16)
  6. // Output:
  7. // string, -42
  8. // string, -2a

func FormatUint

  1. func FormatUint(i uint64, base int) string

FormatUint returns the string representation of i in the given base, for 2 <=
base <= 36. The result uses the lower-case letters ‘a’ to ‘z’ for digit values

= 10.


Example:

  1. v := uint64(42)
  2. s10 := strconv.FormatUint(v, 10)
  3. fmt.Printf("%T, %v\n", s10, s10)
  4. s16 := strconv.FormatUint(v, 16)
  5. fmt.Printf("%T, %v\n", s16, s16)
  6. // Output:
  7. // string, 42
  8. // string, 2a

func IsGraphic

  1. func IsGraphic(r rune) bool

IsGraphic reports whether the rune is defined as a Graphic by Unicode. Such
characters include letters, marks, numbers, punctuation, symbols, and spaces,
from categories L, M, N, P, S, and Zs.

func IsPrint

  1. func IsPrint(r rune) bool

IsPrint reports whether the rune is defined as printable by Go, with the same
definition as unicode.IsPrint: letters, numbers, punctuation, symbols and ASCII
space.


Example:

  1. c := strconv.IsPrint('\u263a')
  2. fmt.Println(c)
  3. bel := strconv.IsPrint('\007')
  4. fmt.Println(bel)
  5. // Output:
  6. // true
  7. // false

func Itoa

  1. func Itoa(i int) string

Itoa is shorthand for FormatInt(int64(i), 10).


Example:

  1. i := 10
  2. s := strconv.Itoa(i)
  3. fmt.Printf("%T, %v\n", s, s)
  4. // Output:
  5. // string, 10

func ParseBool

  1. func ParseBool(str string) (bool, error)

ParseBool returns the boolean value represented by the string. It accepts 1, t,
T, TRUE, true, True, 0, f, F, FALSE, false, False. Any other value returns an
error.


Example:

  1. v := "true"
  2. if s, err := strconv.ParseBool(v); err == nil {
  3. fmt.Printf("%T, %v\n", s, s)
  4. }
  5. // Output:
  6. // bool, true

func ParseFloat

  1. func ParseFloat(s string, bitSize int) (float64, error)

ParseFloat converts the string s to a floating-point number with the precision
specified by bitSize: 32 for float32, or 64 for float64. When bitSize=32, the
result still has type float64, but it will be convertible to float32 without
changing its value.

If s is well-formed and near a valid floating point number, ParseFloat returns
the nearest floating point number rounded using IEEE754 unbiased rounding.

The errors that ParseFloat returns have concrete type *NumError and include
err.Num = s.

If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.

If s is syntactically well-formed but is more than 1/2 ULP away from the largest
floating point number of the given size, ParseFloat returns f = ±Inf, err.Err =
ErrRange.


Example:

  1. v := "3.1415926535"
  2. if s, err := strconv.ParseFloat(v, 32); err == nil {
  3. fmt.Printf("%T, %v\n", s, s)
  4. }
  5. if s, err := strconv.ParseFloat(v, 64); err == nil {
  6. fmt.Printf("%T, %v\n", s, s)
  7. }
  8. // Output:
  9. // float64, 3.1415927410125732
  10. // float64, 3.1415926535

func ParseInt

  1. func ParseInt(s string, base int, bitSize int) (i int64, err error)

ParseInt interprets a string s in the given base (0, 2 to 36) and bit size (0 to
64) and returns the corresponding value i.

If base == 0, the base is implied by the string’s prefix: base 16 for “0x”, base
8 for “0”, and base 10 otherwise. For bases 1, below 0 or above 36 an error is
returned.

The bitSize argument specifies the integer type that the result must fit into.
Bit sizes 0, 8, 16, 32, and 64 correspond to int, int8, int16, int32, and int64.
For a bitSize below 0 or above 64 an error is returned.

The errors that ParseInt returns have concrete type *NumError and include
err.Num = s. If s is empty or contains invalid digits, err.Err = ErrSyntax and
the returned value is 0; if the value corresponding to s cannot be represented
by a signed integer of the given size, err.Err = ErrRange and the returned value
is the maximum magnitude integer of the appropriate bitSize and sign.


Example:

  1. v32 := "-354634382"
  2. if s, err := strconv.ParseInt(v32, 10, 32); err == nil {
  3. fmt.Printf("%T, %v\n", s, s)
  4. }
  5. if s, err := strconv.ParseInt(v32, 16, 32); err == nil {
  6. fmt.Printf("%T, %v\n", s, s)
  7. }
  8. v64 := "-3546343826724305832"
  9. if s, err := strconv.ParseInt(v64, 10, 64); err == nil {
  10. fmt.Printf("%T, %v\n", s, s)
  11. }
  12. if s, err := strconv.ParseInt(v64, 16, 64); err == nil {
  13. fmt.Printf("%T, %v\n", s, s)
  14. }
  15. // Output:
  16. // int64, -354634382
  17. // int64, -3546343826724305832

func ParseUint

  1. func ParseUint(s string, base int, bitSize int) (uint64, error)

ParseUint is like ParseInt but for unsigned numbers.


Example:

  1. v := "42"
  2. if s, err := strconv.ParseUint(v, 10, 32); err == nil {
  3. fmt.Printf("%T, %v\n", s, s)
  4. }
  5. if s, err := strconv.ParseUint(v, 10, 64); err == nil {
  6. fmt.Printf("%T, %v\n", s, s)
  7. }
  8. // Output:
  9. // uint64, 42
  10. // uint64, 42

func Quote

  1. func Quote(s string) string

Quote returns a double-quoted Go string literal representing s. The returned
string uses Go escape sequences (\t, \n, \xFF, \u0100) for control characters
and non-printable characters as defined by IsPrint.


Example:

  1. s := strconv.Quote(`"Fran & Freddie's Diner ☺"`)
  2. fmt.Println(s)
  3. // Output:
  4. // "\"Fran & Freddie's Diner\t☺\""

func QuoteRune

  1. func QuoteRune(r rune) string

QuoteRune returns a single-quoted Go character literal representing the rune.
The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for control
characters and non-printable characters as defined by IsPrint.


Example:

  1. s := strconv.QuoteRune('☺')
  2. fmt.Println(s)
  3. // Output:
  4. // '☺'

func QuoteRuneToASCII

  1. func QuoteRuneToASCII(r rune) string

QuoteRuneToASCII returns a single-quoted Go character literal representing the
rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for
non-ASCII characters and non-printable characters as defined by IsPrint.


Example:

  1. s := strconv.QuoteRuneToASCII('☺')
  2. fmt.Println(s)
  3. // Output:
  4. // '\u263a'

func QuoteRuneToGraphic

  1. func QuoteRuneToGraphic(r rune) string

QuoteRuneToGraphic returns a single-quoted Go character literal representing the
rune. The returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for
non-ASCII characters and non-printable characters as defined by IsGraphic.

func QuoteToASCII

  1. func QuoteToASCII(s string) string

QuoteToASCII returns a double-quoted Go string literal representing s. The
returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII
characters and non-printable characters as defined by IsPrint.


Example:

  1. s := strconv.QuoteToASCII(`"Fran & Freddie's Diner ☺"`)
  2. fmt.Println(s)
  3. // Output:
  4. // "\"Fran & Freddie's Diner\t\u263a\""

func QuoteToGraphic

  1. func QuoteToGraphic(s string) string

QuoteToGraphic returns a double-quoted Go string literal representing s. The
returned string uses Go escape sequences (\t, \n, \xFF, \u0100) for non-ASCII
characters and non-printable characters as defined by IsGraphic.

func Unquote

  1. func Unquote(s string) (string, error)

Unquote interprets s as a single-quoted, double-quoted, or backquoted Go string
literal, returning the string value that s quotes. (If s is single-quoted, it
would be a Go character literal; Unquote returns the corresponding one-character
string.)


Example:

  1. test := func(s string) {
  2. t, err := strconv.Unquote(s)
  3. if err != nil {
  4. fmt.Printf("Unquote(%#v): %v\n", s, err)
  5. } else {
  6. fmt.Printf("Unquote(%#v) = %v\n", s, t)
  7. }
  8. }
  9. s := `\"Fran & Freddie's Diner\t\u263a\"\"`
  10. // If the string doesn't have quotes, it can't be unquoted.
  11. test(s) // invalid syntax
  12. test("`" + s + "`")
  13. test(`"` + s + `"`)
  14. test(`'\u263a'`)
  15. // Output:
  16. // Unquote("\\\"Fran & Freddie's Diner\\t\\u263a\\\"\\\""): invalid syntax
  17. // Unquote("`\\\"Fran & Freddie's Diner\\t\\u263a\\\"\\\"`") = \"Fran & Freddie's Diner\t\u263a\"\"
  18. // Unquote("\"\\\"Fran & Freddie's Diner\\t\\u263a\\\"\\\"\"") = "Fran & Freddie's Diner ☺""
  19. // Unquote("'\\u263a'") = ☺

func UnquoteChar

  1. func UnquoteChar(s string, quote byte) (value rune, multibyte bool, tail string, err error)

UnquoteChar decodes the first character or byte in the escaped string or
character literal represented by the string s. It returns four values:

  1. 1) value, the decoded Unicode code point or byte value;
  2. 2) multibyte, a boolean indicating whether the decoded character requires a multibyte UTF-8 representation;
  3. 3) tail, the remainder of the string after the character; and
  4. 4) an error that will be nil if the character is syntactically valid.

The second argument, quote, specifies the type of literal being parsed and
therefore which escaped quote character is permitted. If set to a single quote,
it permits the sequence \’ and disallows unescaped ‘. If set to a double quote,
it permits \” and disallows unescaped “. If set to zero, it does not permit
either escape and allows both quote characters to appear unescaped.


Example:

  1. v, mb, t, err := strconv.UnquoteChar(`\"Fran & Freddie's Diner\"`, '"')
  2. if err != nil {
  3. log.Fatal(err)
  4. }
  5. fmt.Println("value:", string(v))
  6. fmt.Println("multibyte:", mb)
  7. fmt.Println("tail:", t)
  8. // Output:
  9. // value: "
  10. // multibyte: false
  11. // tail: Fran & Freddie's Diner\"

type NumError

  1. type NumError struct {
  2. Func string // the failing function (ParseBool, ParseInt, ParseUint, ParseFloat)
  3. Num string // the input
  4. Err error // the reason the conversion failed (e.g. ErrRange, ErrSyntax, etc.)
  5. }

A NumError records a failed conversion.


Example:

  1. str := "Not a number"
  2. if _, err := strconv.ParseFloat(str, 64); err != nil {
  3. e := err.(*strconv.NumError)
  4. fmt.Println("Func:", e.Func)
  5. fmt.Println("Num:", e.Num)
  6. fmt.Println("Err:", e.Err)
  7. fmt.Println(err)
  8. }
  9. // Output:
  10. // Func: ParseFloat
  11. // Num: Not a number
  12. // Err: invalid syntax
  13. // strconv.ParseFloat: parsing "Not a number": invalid syntax

func (*NumError) Error

  1. func (e *NumError) Error() string