Skip to content

Go strconv API

Go strconv package — conversions between strings and basic types.

1 class · 6 methods

strconv

6 methods

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

strconv.Atoi(s string) (int, error)

Convert string to int. Returns error if s is not a valid integer.

Parameters

NameTypeDescription
sstringString to parse.

Returns

(int, error)

Example

go
n, err := strconv.Atoi("42")    // n == 42, err == nil
_, err = strconv.Atoi("4.2")    // err != nil
_, err = strconv.Atoi("abc")    // err != nil
strconv.Itoa(i int) string

Convert int to its decimal string representation.

Parameters

NameTypeDescription
iintInteger to convert.

Returns

string

Example

go
strconv.Itoa(42)    // "42"
strconv.Itoa(-7)    // "-7"
strconv.ParseFloat(s string, bitSize int) (float64, error)

Convert string to a floating-point number with the precision specified by bitSize (32 or 64).

Parameters

NameTypeDescription
sstringString to parse.
bitSizeint32 or 64.

Returns

(float64, error)

Example

go
f, err := strconv.ParseFloat("3.14", 64)  // f == 3.14
_, err = strconv.ParseFloat("abc", 64)    // err != nil
strconv.ParseInt(s string, base int, bitSize int) (int64, error)

Convert string in the given base (0, 2..36) to a signed integer.

Parameters

NameTypeDescription
sstringString to parse.
baseintBase (0 = auto-detect from prefix).
bitSizeint0..64.

Returns

(int64, error)

Example

go
n, _ := strconv.ParseInt("ff", 16, 64)  // n == 255
n, _ = strconv.ParseInt("0b11", 0, 64)  // n == 3 (auto base)
strconv.FormatFloat(f float64, fmt byte, prec, bitSize int) string

Convert float to string. fmt is one of 'b','e','E','f','g','G','x','X'.

Parameters

NameTypeDescription
ffloat64Number to format.
fmtbyteFormat verb.
precintPrecision (-1 for shortest).
bitSizeint32 or 64.

Returns

string

Example

go
strconv.FormatFloat(3.14, 'f', 2, 64)  // "3.14"
strconv.FormatFloat(3.14, 'g', -1, 64)  // "3.14"
strconv.FormatInt(i int64, base int) string

Convert int64 to string in the given base (2..36).

Parameters

NameTypeDescription
iint64Integer to format.
baseintBase (2..36).

Returns

string

Example

go
strconv.FormatInt(255, 16)  // "ff"
strconv.FormatInt(10, 2)    // "1010"