Conversion between go language string and numeric type

Keywords: Go Back-end

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

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:

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

The operation results are as follows:

type:string value:"100"

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 that Atoi() function has two return values. i is the integer of successful conversion, err is null if successful conversion, and is the corresponding error message if conversion fails

Examples are as follows:

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!\n%v\n", str2, err)//Print out the reason for conversion failure
	} else {
		fmt.Printf("type:%T value:%#v\n", num2, num2)
	}
}

Operation results:

type:int value:110
s100 Conversion failed!
strconv.Atoi: parsing "s100": invalid syntax

Parse series functions

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

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)

The example code is as follows

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)
    }
}

The operation results are as follows:

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

ParseInt()

The ParseInt() 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 the syntax is wrong, err.Error = ErrSyntax. If the result exceeds the type range, err.Error = ErrRange

The example code is as follows:

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

The operation results are as follows:

-11

ParseUint

The function of ParseUint() function is similar to ParseInt() function, but ParseUint() function does not accept 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 examples are as follows:

func main() {
    str := "11"
    num, err := strconv.ParseUint(str, 10, 0)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Println(num)
    }
}

Operation results:

11

ParseFloat()

ParseFloat() function is used to convert a string representing a floating point number to float type. The 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 incorrect, err.Error=ErrSyntax. If the return value exceeds the representation range, the return value f is ± Inf, err.Error= ErrRange

Code examples are as follows:

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

Operation results:

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

Format series functions

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

FormatBool()

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

func FormatBool(b bool) string

The example code is as follows:

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

The operation results are as follows:

type:string,value:true

FormatInt()

FormatInt() 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

The parameter i must be of type int64, the parameter base must be between 2 and 36, and the returned result will use lowercase letters "a" to "z" to represent numbers greater than 10

Example code:

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

The operation results are as follows:

type:string,value:64

FormatUint()

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

func FormatUint(i uint64, base int) string

The example code is as follows:

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

The operation results are as follows:

type:string,value:6e

FormatFloat

The FormatFloat() 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 indicates format, which can be set as "f" indicates - ddd.dddd, "b" indicates - ddddp ± DDD, index is binary, "e" indicates - d.dddde ± dd decimal index, "e" indicates - d.dddde ± dd decimal index, "g" indicates "e" format when index is large, otherwise "f" lattice, "g" indicates "e" format when index is large, otherwise "f" format is used
  • 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

The code example is as follows

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

The operation results are as follows

type:string,value:3.1415926E+00

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(), AppendUint()

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

The code example is as follows

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))
}

Operation results:

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

Posted by tam2000k2 on Sat, 06 Nov 2021 03:55:54 -0700