strconv
Before You Start
- Applies to: Go 1.21+ (examples verified with Go 1.22) · Prerequisites: Base: Data Types · Read time: about 10 min
Official documentation: strconv package - strconv - Go Packages
The strconv package implements conversions between string representations and basic data types.
Import
import (
"strconv"
)The following will demonstrate how to use it with examples.
String to Integer
func Atoi(s string) (int, error)s- The string to convert
func TestAoti(t *testing.T) {
ints, err := strconv.Atoi("456789")
fmt.Println(ints, err)
}=== RUN TestAoti
456789 <nil>
--- PASS: TestAoti (0.00s)
PASSInteger to String
func Itoa(i int) stringi- The integer to convert
func TestIota(t *testing.T) {
str := strconv.Itoa(114)
fmt.Println(str)
}=== RUN TestIota
114
--- PASS: TestIota (0.00s)
PASSString to Boolean
func ParseBool(str string) (bool, error)s- The string to convert
Strings that can be converted are as follows:
"1", "t", "T", "true", "TRUE", "True" // true
"0", "f", "F", "false", "FALSE", "False" // falsefunc TestAtob(t *testing.T) {
parseBool, err := strconv.ParseBool("1")
fmt.Println(parseBool, err)
b, err := strconv.ParseBool("true")
fmt.Println(b, err)
b2, err := strconv.ParseBool("FALSE")
fmt.Println(b2, err)
}=== RUN TestAotb
true <nil>
true <nil>
false <nil>
--- PASS: TestAotb (0.00s)
PASSBoolean to String
func FormatBool(b bool) stringb- Boolean value
func TestBota(t *testing.T) {
fmt.Println(strconv.FormatBool(true))
fmt.Println(strconv.FormatBool(false))
}=== RUN TestBota
true
false
--- PASS: TestBota (0.00s)
PASSConvert to Go String
Both will convert a string to a quoted Go string. The difference is that the latter escapes non-ASCII characters via \u.
func TestQuote(t *testing.T) {
fmt.Println(strconv.Quote("hello 世界"))
fmt.Println(strconv.QuoteToASCII("hello 世界"))
}=== RUN TestQuote
"hello 世界"
"hello \u4e16\u754c"
--- PASS: TestQuote (0.00s)
PASSString to Float
func ParseFloat(s string, bitSize int) (float64, error)s- The string to convertbitSize- Bit size
func TestParseFloat(t *testing.T) {
float, err := strconv.ParseFloat("1.145114", 64)
fmt.Println(float, err)
float, err = strconv.ParseFloat("2.3333333333333333333", 64)
fmt.Println(float, err)
}=== RUN TestFloat
1.145114 <nil>
2.3333333333333335 <nil>
--- PASS: TestFloat (0.00s)
PASSFloat to String
When converting floats to strings, the official provides several format methods to output different styles.
// 'b' (-ddddp±ddd, binary exponent),
// 'e' (-d.dddde±dd, lowercase e decimal exponent),
// 'E' (-d.ddddE±dd, uppercase E decimal exponent),
// 'f' (-ddd.dddd, no exponent), // Generally use this one without special requirements
// 'g' (use 'e' format for large exponents, 'f' format for small exponents),
// 'G' (use 'E' format for large exponents, 'f' format for small exponents),
// 'x' (-0xd.ddddp±ddd, hexadecimal fraction and binary exponent),
// 'X' (-0Xd.ddddP±ddd, hexadecimal fraction and binary exponent).Conversion function:
func FormatFloat(f float64, fmt byte, prec, bitSize int) string- f - The float to convert
- fmt - Format type
- prec - Precision, except for
g/Gcases where it indicates maximum significant digits, in other cases it indicates decimal places to retain - bitSize - Bit size
Of course, in general, f is most commonly used for direct decimal conversion.
func TestFormatFloat(t *testing.T) {
f := 1315643.14159261234567891011
fmt.Println(strconv.FormatFloat(f, 'f', 6, 64))
fmt.Println(strconv.FormatFloat(f, 'b', 6, 64))
fmt.Println(strconv.FormatFloat(f, 'e', 6, 64))
fmt.Println(strconv.FormatFloat(f, 'x', 6, 64))
fmt.Println(strconv.FormatFloat(f, 'g', 6, 64))
fmt.Println(strconv.FormatFloat(1.111, 'g', 6, 64))
}=== RUN TestFormatFloat
1315643.141593
5650644266346967p-32
1.315643e+06
0x1.4133b2p+20
1.31564e+06
1.111
--- PASS: TestFormatFloat (0.00s)
PASSString to Complex
func ParseComplex(s string, bitSize int) (complex128, error)s- The string to convertbitSize- Bit size
func TestParseComplex(t *testing.T) {
fmt.Println(strconv.ParseComplex("1+2i", 128))
fmt.Println(strconv.ParseComplex("1+2j", 128))
}=== RUN TestParseComplex
(1+2i) <nil>
(0+0i) strconv.ParseComplex: parsing "1+2j": invalid syntax
--- PASS: TestParseComplex (0.00s)
PASSComplex to String
func FormatComplex(c complex128, fmt byte, prec, bitSize int) stringc - Complex number
fmt - Format type, refer to float format type
prec - Refer to float precision
bitSize - Bit size
func TestFormatComplex(t *testing.T) {
fmt.Println(strconv.FormatComplex(complex(1.1, 12), 'f', 2, 128))
fmt.Println(strconv.FormatComplex(complex(5.6, 2.8), 'b', 2, 128))
fmt.Println(strconv.FormatComplex(complex(18.88999, 89.7), 'g', 2, 128))
}=== RUN TestFormatComplex
(1.10+12.00i)
(6305039478318694p-50+6305039478318694p-51i)
(19+90i)
--- PASS: TestFormatComplex (0.00s)
PASSAppend Data to String
In other languages like Java, the result of "1"+1 is "11". Java automatically completes the type conversion, but such operations are not allowed in Go because the two data types are different. Therefore, you need to use the Append functions under strconv. The specific parameters are consistent with the data conversion functions above.
func TestAppend(t *testing.T) {
bytes := []byte("Here is some data:")
bytes = strconv.AppendInt(bytes, 10, 10)
bytes = strconv.AppendFloat(bytes, 1.2222, 'f', 2, 64)
bytes = strconv.AppendBool(bytes, false)
fmt.Println(string(bytes))
}=== RUN TestAppend
Here is some data:101.22false
--- PASS: TestAppend (0.00s)
PASSComplete Example
The program below runs as-is: copy it into a file and execute go run main.go, or paste it into the Go Playground.
package main
import (
"fmt"
"strconv"
)
func main() {
i, err := strconv.Atoi("42")
fmt.Println(i, err)
f, _ := strconv.ParseFloat("3.14", 64)
fmt.Println(f)
fmt.Println(strconv.Itoa(255), strconv.FormatInt(255, 2))
q := strconv.Quote("go\tlang")
fmt.Println(q)
v, _ := strconv.ParseBool("true")
fmt.Println(v)
}Expected output:
42 <nil>
3.14
255 11111111
"go\tlang"
trueCommon Pitfalls
- Always check the error. On failure,
Parse*returns the zero value; ignoring the error hides bad input. Atoiis base 10 only. Other bases needParseInt(s, base, bitSize)(base 2–36).Quoteproduces a Go string literal. It escapes tabs and quotes, which is what you want for code, not for display.- Use
Append*to avoid allocations.strconv.AppendInt(buf, n, 10)appends into an existing byte slice. - Beware of bit sizes.
ParseInt(s, 10, 8)rejects values outsideint8; choose the size deliberately.
Change Log
- 2026-10-14: Added "Before You Start" notes, a complete runnable example with expected output, common pitfalls, and this change log. Closed a code block that was left unterminated.
