strconv (type conversion) of Go standard library

reference resources:   Go language strconv package: conversion between string and numeric types

In actual development, we often need to convert some common data types, such as string, int, int64, float and other data types. The strconv package in Go language provides us with the conversion function between string and basic data types.

The functions commonly used in strconv package include Atoi(), Itia(), parse series functions, format series functions, append series functions, etc. Let's introduce them respectively.

1. Conversion between string and int types

The conversion between string and integer is the most commonly used in our programming. Here are the specific operations.

1.1 Itoa(): integer to string

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

func Itoa(i int) string

Code examples are as follows:

package main

import (
	"fmt"
	"strconv"
)

func main() {
	num := 100
	str := strconv.Itoa(num)
	fmt.Printf("type:%T ---- value:%#v\n", str, str) // type:string ---- value:100
}

1.2 Atoi(): string to integer

Atoi() function is used to convert an integer of string type to int type. The function signature is as follows.

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

It can be seen from the function signature   Atoi()   Function has two return values,   i   To convert to a successful integer,   err   If the conversion is successful or null, the corresponding error message will be displayed when the conversion fails.

Code example:

package main

import (
	"fmt"
	"strconv"
)

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

	num1, err := strconv.Atoi(str1)
	if err != nil {
		fmt.Printf("%v Conversion failed!", str1)
	} else {
		fmt.Printf("type:%T value:%#v\n", num1, num1)
	}

	num2, err := strconv.Atoi(str2)
	if err != nil {
		fmt.Printf("%v Conversion failed!", str2)
	} else {
		fmt.Printf("type:%T value:%#v\n", num2, num2)
	}
}

Output results:

type:int value:110
s100 Conversion failed!

1.3 fmt.Sprintf other types to string

Other types can be converted into string types. In addition to strconv package, fmt.Sprintf function can also be used:

package main

import (
    "fmt"
)

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

2. Parse series functions


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

2.1 ParseBool()


ParseBool() function is used to convert a string to a value of bool type. It can only accept 1, 0, t, F, t, F, true, false, true, false, true and false. Other values return errors. The function signature is as follows.

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

Code example:

func main() {
	str1 := "110"

	boo1, err := strconv.ParseBool(str1)
	if err != nil {
		fmt.Printf("str1: %v\n", err)
	} else {
		fmt.Println(boo1)
	}

	str2 := "t"
	boo2, err := strconv.ParseBool(str2)
	if err != nil {
		fmt.Printf("str2: %v\n", err)
	} else {
		fmt.Println(boo2)
	}
}

Output results:

str1: strconv.ParseBool: parsing "110": invalid syntax
true

2.2 ParseInt()

ParseInt()   The function is used to return an integer value represented by a string (which can contain a sign). The function signature is as follows:

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

Parameter Description:

Base specifies base, with a value range of 2 to 36. If base is 0, it will be judged from the string prefix, "0x" is hexadecimal, "0" is octal, otherwise it is hexadecimal.
bitSize specifies that the result must be an integer type without overflow assignment. 0, 8, 16, 32 and 64 represent int, int8, int16, int32 and int64 respectively.
The returned err is of type * NumErr. If there is a syntax error, err.Error = ErrSyntax. If the result exceeds the type range, err.Error = ErrRange.
Code example:

func main() {
	str := "-11"

	num, err := strconv.ParseInt(str, 10, 0)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(num)
	}
}

Output results:

-11

2.3 ParseUnit()

ParseUint()   The function is similar to   ParseInt()   Function, but   ParseUint()   The function does not accept signs. It 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 := strconv.ParseUint(str, 10, 0)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(num) // 11
	}
}

2.4 ParseFloat()

ParseFloat()   The function converts a string representing a floating-point number to   float   Type, function signature is as follows.

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

Parameter Description:

If s conforms to the syntax rules, the function returns a floating-point number closest to the value represented by s (rounded using the IEEE754 specification).
bitSize specifies the type of return value. 32 represents float32 and 64 represents float64;
The return value err is of type * NumErr. If the syntax is wrong, err.Error=ErrSyntax. If the return value exceeds the representation range, the return value f is ± Inf, err.Error= ErrRange.

func main() {
	str := "3.1415926"
	num, err := strconv.ParseFloat(str, 64)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Println(num)	// 3.1415926
	}

}

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 conversion failure.

3. Format series functions


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

3.1 FormatBool()


The FormatBool() function can convert the value of a bool type to the corresponding string type. The function signature is as follows.

func FormatBool(b bool) string

Code example:

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

3.2 FormatInt()

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

func FormatInt(i int64, base int) string

Where, parameter   i   Must be   int64   Type, parameter   base   It must be between 2 and 36. The lowercase parent "a" to "z" will be used in the returned result to represent numbers greater than 10.

Code example:

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

3.3 FormatUint()

FormatUint()   Function and   FormatInt()   The functions are similar, but the parameters   i   Must be unsigned   uint64   Type, function signature is as follows.

func FormatUint(i uint64, base int) string

Example code:

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

3.4 FormatFloat()

FormatFloat()   The function is used to convert a floating-point number to a string type. The function signature is as follows:

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

Parameter Description:

bitSize indicates the source type of parameter f (32 indicates float32 and 64 indicates float64), which will be rounded accordingly.
fmt represents the format, which can be set to "f" for - ddd.dddd, "b" for - ddddp ± DDD, the index is binary, "e" for - d.dddde ± dd decimal index, "e" for - d.dddde ± dd decimal index, "g" for "e" format when the index is large, otherwise "f" lattice, "g" for "e" format when the index is large, otherwise "f" format.
Prec control accuracy (excluding exponential part): when the parameter fmt is "f", "e", "e", it represents the number of digits after the decimal point; When the parameter fmt is "g" and "g", it controls the total number of numbers. If prec is - 1, it means that the minimum number of necessary numbers are used to represent f.
Code example:

func main() {
	var num float64 = 3.1415926
	str := strconv.FormatFloat(num, 'E', -1, 64)
	fmt.Printf("type:%T,value:%v\n ", str, str)
	// type:string,value:3.1415926E+00
}

4. Append series functions


Append series functions are used to convert the specified type into a string and append it to a slice, including AppendBool(), AppendFloat(), AppendInt(), and 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):")

	// Append the string converted to hexadecimal to slice
	b10 = strconv.AppendInt(b10, -42, 10)
	fmt.Println(string(b10))
	b16 := []byte("int (base 16):")
	b16 = strconv.AppendInt(b16, -42, 16)
	fmt.Println(string(b16))
}

Output:

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

Tags: Go

Posted on Mon, 18 Oct 2021 03:06:37 -0400 by nakkaya