SoFunction
Updated on 2025-03-05

Detailed explanation of the use of Go language strconv and other basic data type conversion functions

Preface

Previous articleLearn about the common functions and methods of Go standard library strings in one articleIntroductionstringsSome commonly used functions and methods in the database are also used in this articlestringType-centric, bystrconvStandard library, introducing functions that convert with other basic data types.

strconv

strconvPackage providedstringFunctions that convert between types and other basic data types will not be introduced in this article. If you want to know more, you can go toGo package documentationCheck.

Conversion between string and int

Itoa: int type to string type

Itoa(i int) string

  • parameteriis the number to be converted.
  • The return value is the converted string.
import (
	"fmt"
	"strconv"
)

func main() {
	num := 16
	str := (num)
	("Type: %T, value: %s", str, str) // Type: string, value: 16}

Atoi: string type to int type

Atoi(s string) (int, error)

  • The parameter of the function is the string to be converted
  • There are two return values, the first is the converted plastic number, and the second is the wrong description.
import (
	"fmt"
	"strconv"
)

func main() {
	str := "666"
	num, err := (str)
	if err != nil {
		("err: ", ())
		return
	}
	("Type: %T, value: %d", num, num) // Type: int, value: 666}

This function isItoaCompared to the function, there is one moreerrorReturn value because if the string is passed in, it cannot be converted into a number, for example1a1, this function will returnNumErrorError, andItoaFunctions, no matter what kind of number they are passed in, can be converted tostring, so there is noerrorThe statement.

FormatInt: Converts a number to a specified binary number and returns as string type

FormatInt(i int64, base int) string

  • The first parameter is the specified number, the type isint64
  • The second parameter is the specified binary
  • The third parameter is a string after converting the number into a specified number.
import (
	"strconv"
)

func main() {
	var num int64 = 2
	str := (num, 2)
	var num2 int64 = 17
	str2 := (num2, 16)
	println(str)  // 10
	println(str2) // 11
}

The above code implements the number2Convert to binary form10, turn the number17Convert to hexadecimal form11, and return as string type. All the above numbers represent signsint64Type, corresponding to it is unsigneduint64Convert function of typeFormatUint

ParseInt: Given the cardinality (digital number) and digits, return the corresponding decimal value.

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

  • The first parametersFor the string to be parsed
  • The second parameterbaseis the cardinality, that is, the02arrive36Category.
  • The third parameterbitSizeis the number of digits,08163264Corresponding to the bitsintint8int16int32int64. ifbitSizeLess than0Or greater than64, an error is returned.
  • The first return valueiThe number after conversion
  • The second return valueerrFor error messages generated during conversion, exceptbitSizeLess than0Or greater than64, an error will occur except if the passed stringsandbaseParameter orbitSizeIf the parameters do not match, an error will also occur.
import (
	"fmt"
	"strconv"
)

func main() {
	parseInt, err := ("100", 2, 64)
	if err != nil {
		(())
		return
	}
	println(parseInt) // 4

	parseInt2, err := ("666", 2, 64)
	if err != nil {
		(()) // : parsing "666": invalid syntax
		return
	}
	println(parseInt2)
}

First, put the binary100Convert to decimal system,4, and then binary666Convert to decimal, but the number corresponding to the binary does not have 666, so the conversion error is returned: parsing "666": invalid syntaxerror message. Corresponding to this is the return unsigned bituint64Convert function of typeParseUint

Conversion between string and float

ParseFloat: String type to floating point type

ParseFloat(s string, bitSize int) (float64, error)

  • The first parametersis a string with conversion.
  • The second parameter isbitSizeis the converted number of bits,32representfloat3264representfloat64
  • The first return value is the converted floating point number.
  • The second return value is an error generated during the conversion process
import (
	"fmt"
	"strconv"
)

func main() {
	num, err := ("11.05", 64)
	if err != nil {
		return
	}
	(num)
}

If thesSyntax errors such as1s1, the conversion fails and returnserror

FormatFloat: Convert floating point number f to string according to format fmt and precision prec

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

  • The first parameterfis the floating point number to be converted.
  • The second parameter is format, optional values ​​areb e E f g G x X
  • The third parameterprecFor precision, it is accurate to several decimal places.
  • The return value is the converted string.
import (
	"fmt"
	"strconv"
)

func main() {
	str := (5.26, 'f', 1, 64)
	(str) // 5.3
}

FormatFloatThe function will round the result value.

Conversion between string and bool

ParseBool: string to boolean

ParseBool(str string) (bool, error)

  • The first parameterstrFor the string to be converted
  • The first return value is after the conversionboolvalue
  • The second return value is an error generated during conversion.
import (
	"fmt"
	"strconv"
)

func main() {
	bool1, err := ("true")
	if err != nil {
		(())
		return
	}
	(bool1) // true

	bool2, err := ("golang")
	if err != nil {
		(()) // : parsing "golang": invalid syntax
		return
	}
	(bool2)
}

The first stringtrueThe Boolean value was successful, but the second stringgolangThe Boolean value failed becauseboolThe optional value of type is onlytrueandfalse, other values ​​cannot be converted to boolean values.

FormatBool: Boolean to string

FormatBool(b bool) string

  • parameterbis a Boolean value with conversion.
  • The return value is the converted string.
import (
	"fmt"
	"strconv"
)

func main() {
	boolStr := (true)
	(boolStr) // "true"
}

summary

This articlestringandinttype,floatTypes andboolIntroduction to functions that convert types to each other, master the usage of these functions, and deal with developmentstringScenarios where types are converted to other basic data types are not a problem.

This is the article about the detailed explanation of the use of Go strconv and other basic data type conversion functions. For more related Go strconv content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!