SoFunction
Updated on 2025-03-03

The use of strconv in Go language standard library

The strconv package in Go language implements the mutual conversion of basic data types and their string representations.

The strconv package implements the conversion of basic data types and their string representations, mainly including the following commonly used functions: Atoi(), Itia(), parse series, format series, append series.

1. Conversion between string and int type

The conversion between strings and integers is the most commonly used in programming. Let’s introduce the specific operations below.

1.1 Itoa(): Integer to string

The Itoa() function is used to convert int type data into the corresponding string type, and the function signature is as follows.

func Itoa(i int) string

The code example is as follows:

package main
 
import (
    "fmt"
    "strconv"
)
 
func main() {
    num := 100
    str := (num)
    ("Type: %T, Value: %v\n", str, str) // Type: string, value: 100}

1.2 Atoi(): String to integer

The Atoi() function is used to convert integers of string type to int type, and the function signature is as follows.

func Atoi(s string) (i int, err error)

Through the function signature, we can see that the Atoi() function has two return values. i is the integer that has been successfully converted, and err is the corresponding error message when the conversion is successful and the conversion fails.

Code example:

func main() {
    str1 := "110"
    str2 := "s100"

    num1, err := (str1)
    if err != nil {
        ("%v conversion failed!", str1)
    } else {
        ("Type: %T, Value: %v\n", num1, num1)
    }

    num2, err := (str2)
    if err != nil {
        ("%v conversion failed!", str2)
    } else {
        ("Type: %T, Value: %v\n", num2, num2)
    }
}

Output:

Type: int, value: 110
s100 conversion failed!

1.3 Other types to string

In addition to using the strconv package, you can also use functions when converting other types to string types:

package main
 
import (
    "fmt"
)
 
func main() {
    s2 := ("%d", 456)
    println(s2)
}

2. Parse series functions

The Parse series functions are used to convert a string to a value of a specified type, including ParseBool() , ParseFloat() , ParseInt() , and ParseUint() .

2.1 ParseBool()

The ParseBool() function is used to convert a string to a value of type bool. It can only accept 1 , 0 , t , f , T , F , true , false , True , False , TRUE , FALSE . Other values ​​all return errors, and the function signature is as follows.

func ParseBool(str string) (value bool, err error)

Code example:

func main() {
    str1 := "110"
 
    boo1, err := (str1)
    if err != nil {
        ("str1: %v\n", err)
    } else {
        (boo1)
    }
 
    str2 := "t"
    boo2, err := (str2)
    if err != nil {
        ("str2: %v\n", err)
    } else {
        (boo2)
    }
}

Output:

str1: : parsing "110": invalid syntax
true

2.2 ParseInt()

The ParseInt() function is used to return the integer value represented by a string (can contain positive and negative signs). The function signature is as follows:

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

Parameter description:

  • base specifies the binary system, with a value range of 2 to 36. If base is 0, it will be judged from the pre-standard, "0x" is hexadecimal, "0" is angular, otherwise it is decimal.
  • bitSize specifies that the integer type that the result must be able to be assigned without overflow. 0, 8, 16, 32, 64 represent int , int8 , int16 , int32 , and int64 respectively.
  • The returned err is of type *NumErr, if the syntax is wrong, = ErrSyntax, if the result is outside the type range = ErrRange.

Code example:

func main() {
    str := "-11"
 
    num, err := (str, 10, 0)
    if err != nil {
        (err)
    } else {
        (num)
    }
}

2.3 ParseUnit()

The function of the ParseUint() function is similar to the ParseInt() function, but the ParseUint() function does not accept positive and negative signs and is used for unsigned integers. The function signature is as follows:

func ParseUint(s string, base int, bitSize int) (n uint64, err error)

Code example:

func main() {
    str := "11"
 
    num, err := (str, 10, 0)
    if err != nil {
        (err)
    } else {
        (num) // 11
    }
}

2.4 ParseFloat()

The ParseFloat() function is used to convert a string representing a floating point number to a float type, and the function signature is as follows.

func ParseFloat(s string, bitSize int) (f float64, err error)

Parameter description:

  • If s complies with syntax rules, the function returns a floating point number closest to s representing the value (rounded using the IEEE754 specification).
  • bitSize specifies the type of return value, 32 means float32, 64 means float64;
  • The return value err is of type *NumErr. If the syntax is wrong, =ErrSyntax , if the return value exceeds the representation range, the return value f is ±Inf, = ErrRange .
func main() {
    str := "3.1415926"
    num, err := (str, 64)
    if err != nil {
        (err)
    } else {
        (num)    // 3.1415926
    }
}

The Parse series functions have two return values. The first return value is the converted value, and the second return value is the error message of the conversion failure.

3. Format series functions

The Format series functions implement the function of formatting the given type of data into string types, including FormatBool() , FormatInt() , FormatUint() , FormatFloat() .

3.1 FormatBool()

The FormatBool() function can be converted into the corresponding string type by a bool type, and the function signature is as follows.

func FormatBool(b bool) string

Code example:

func main() {
    num := true
    str := (num)
    ("type:%T,value:%v\n ", str, str)
    // type:string,value:true
}

3.2 FormatInt()

The FormatInt() function is used to convert integer data into a specified binary and return it as a string. The function signature is as follows:

func FormatInt(i int64, base int) string

Among them, parameter i must be of type int64, parameter base must be between 2 and 36, and lowercase parent "a" to "z" will be used to represent numbers greater than 10.

Code example:

func main() {
    var num int64 = 100
    str := (num, 16)
    ("type:%T,value:%v\n ", str, str)
    // type:string,value:64
}

3.3 FormatUint()

The FormatUint() function is similar to the FormatInt() function, but the parameter i must be of the unsigned uint64 type, and the function signature is as follows.

func FormatUint(i uint64, base int) string

Sample code:

func main() {
    var num uint64 = 110
    str := (num, 16)
    ("type:%T,value:%v\n ", str, str)
    // type:string,value:6e
}

3.4 FormatFloat()

The FormatFloat() function is used to convert floating point numbers to string types, and the function signature is as follows:

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

Parameter description:

  • bitSize represents the source type of parameter f (32 means float32, 64 means float64), and will be rounded accordingly.
  • fmt represents the format, which can be set to "f" for -, "b" for -ddddp±ddd, the exponent is binary, "e" for -±dd decimal exponent, "E" for -±dd decimal exponent, "g" for large exponents, use "e" format, otherwise use "f" format, and "G" for large exponents, use "E" format, otherwise use "f" format.
  • prec controls accuracy (excluding exponential part): When the parameters fmt are "f", "e", and "E", it represents the number of numbers after the decimal point; when the parameters fmt are "g" and "G", it controls the total number of numbers. If prec is -1, it means that f is represented by the minimum number of but necessary numbers.
func main() {
    var num float64 = 3.1415926
    str := (num, 'E', -1, 64)
    ("type:%T,value:%v\n ", str, str)
    // type:string,value:3.1415926E+00
}

4. Append series functions

The Append series functions are used to convert the specified type into a string and then append it to a slice, including AppendBool() , AppendFloat() , AppendInt() , AppendUint() .

The Append series functions are similar to the Format series functions, except that the converted results are appended to a slice.

package main
 
import (
    "fmt"
    "strconv"
)
 
func main() {
    // Declare a slice    b10 := []byte("int (base 10):")
 
    // Convert to decimal string and append to slice    b10 = (b10, -42, 10)
    (string(b10))
    b16 := []byte("int (base 16):")
    b16 = (b16, -42, 16)
    (string(b16))
}

Output:

int (base 10):-42
int (base 16):-2a

This is the end of this article about the use of strconv in the Go language standard library. For more relevant content on using Go strconv, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!