strconv
6 methodsPackage 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
| Name | Type | Description |
|---|---|---|
| s | string | String 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 != nilstrconv.Itoa(i int) stringConvert int to its decimal string representation.
Parameters
| Name | Type | Description |
|---|---|---|
| i | int | Integer 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
| Name | Type | Description |
|---|---|---|
| s | string | String to parse. |
| bitSize | int | 32 or 64. |
Returns
(float64, error)
Example
go
f, err := strconv.ParseFloat("3.14", 64) // f == 3.14
_, err = strconv.ParseFloat("abc", 64) // err != nilstrconv.ParseInt(s string, base int, bitSize int) (int64, error)Convert string in the given base (0, 2..36) to a signed integer.
Parameters
| Name | Type | Description |
|---|---|---|
| s | string | String to parse. |
| base | int | Base (0 = auto-detect from prefix). |
| bitSize | int | 0..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) stringConvert float to string. fmt is one of 'b','e','E','f','g','G','x','X'.
Parameters
| Name | Type | Description |
|---|---|---|
| f | float64 | Number to format. |
| fmt | byte | Format verb. |
| prec | int | Precision (-1 for shortest). |
| bitSize | int | 32 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) stringConvert int64 to string in the given base (2..36).
Parameters
| Name | Type | Description |
|---|---|---|
| i | int64 | Integer to format. |
| base | int | Base (2..36). |
Returns
string
Example
go
strconv.FormatInt(255, 16) // "ff"
strconv.FormatInt(10, 2) // "1010"