Home >Backend Development >Golang >How to convert string to int type in go language

How to convert string to int type in go language

青灯夜游
青灯夜游Original
2021-03-15 14:00:3746395browse

Conversion method: 1. Use the Atoi() function in the strconv package to convert the integer of the string type into the int type, with the syntax "strconv.Atoi(string)"; 2. Use the Atoi() function in the strconv package The ParseInt() function can return an integer value represented by a string (accepting positive and negative signs), and the syntax is "strconv.ParseInt(string,10,64)".

How to convert string to int type in go language

The operating environment of this tutorial: windows10 system, GO 1.18, thinkpad t480 computer.

How to convert strings to various int types in golang

Convert string to int:

int, err := strconv.Atoi(string)

string to int64:

int64, err := strconv.ParseInt(string, 10, 64)

int to string:

string := strconv.Itoa(int)

int64 to string:

string := strconv.FormatInt(int64,10)

Go language strconv (type conversion) Introduction

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

strconv package

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

Please check the official documentation for more functions.

String and int type conversion

This set of functions is the most commonly used in our daily programming.

Atoi()

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

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

If the incoming string parameter cannot be converted to int type, an error will be returned.

s1 := "100"
i1, err := strconv.Atoi(s1)
if err != nil {
    fmt.Println("can't convert to int")
} else {
    fmt.Printf("type:%T value:%#v\n", i1, i1) //type:int value:100
}

Itoa()

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

func Itoa(i int) string

The sample code is as follows:

i2 := 200s2 := strconv.Itoa(i2)fmt.Printf("type:%T value:%#v\n", s2, s2) //type:string value:"200"

Parse series function

Parse class function is used to convert a string to a given Values ​​of type: ParseBool(), ParseFloat(), ParseInt(), ParseUint().

ParseBool()

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

Returns the bool value represented by a string. It accepts 1, 0, t, f, T, F, true, false, True, False, TRUE, FALSE; otherwise it returns an error.

ParseInt()

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

Returns an integer value represented by a string, accepting positive and negative signs.

base specifies the base (2 to 36). If base is 0, it will be judged from the prefix of the string. "0x" is hexadecimal, "0" is octal, otherwise it is decimal. System;

bitSize specifies the integer type that the result must be assigned without overflow, 0, 8, 16, 32, and 64 respectively represent int, int8, int16, int32, and int64;

The err returned It is of type *NumErr. If the syntax is incorrect, err.Error = ErrSyntax; if the result exceeds the type range, err.Error = ErrRange.

ParseUnit()

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

ParseUintSimilar to ParseInt but does not accept signs, used for unsigned integers .

ParseFloat()

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

Parse a string representing a floating point number and return its value.

If s conforms to the grammatical rules, the function will return a floating point number closest to the value represented by s (using IEEE754 standard rounding).

bitSize specifies the expected receiving type, 32 is float32 (the return value can be assigned to float32 without changing the exact value), 64 is float64;

The return value err is of *NumErr type, If the syntax is incorrect, err.Error=ErrSyntax; if the result exceeds the representation range, the return value f is ±Inf, and err.Error=ErrRange.

Code example

b, err := strconv.ParseBool("true")
f, err := strconv.ParseFloat("3.1415", 64)
i, err := strconv.ParseInt("-2", 10, 64)
u, err := strconv.ParseUint("2", 10, 64)

These functions have two return values. The first return value is the converted value, and the second return value is the converted value. error message.

Format series functions

The Format series functions implement the function of formatting a given type of data into string type data.

FormatBool()

func FormatBool(b bool) string

Returns "true" or "false" according to the value of b.

FormatInt()

func FormatInt(i int64, base int) string

Returns the base base string representation of i. base must be between 2 and 36, and lowercase letters 'a' to 'z' will be used in the result to represent numbers greater than 10.

FormatUint()

func FormatUint(i uint64, base int) string

is the unsigned integer version of FormatInt.

FormatFloat()

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

The function represents a floating point number as a string and returns it.

bitSize represents the source type of f (32: float32, 64: float64), and will be rounded accordingly.

fmt representation format: 'f' (-ddd.dddd), 'b' (-ddddp±ddd, exponent is binary), 'e' (-d.dddde±dd, decimal exponent), ' E' (-d.ddddE±dd, decimal exponent), 'g' (use 'e' format when the exponent is very large, otherwise 'f' format), 'G' (use 'E' format when the exponent is very large, otherwise 'f' format).

prec controls precision (excluding the exponent part): for 'f', 'e', ​​'E', it represents the number of digits after the decimal point; for 'g', 'G', it controls the total Number of digits. If prec is -1, it means using the minimum number of numbers necessary to represent f.

Code Example

s1 := strconv.FormatBool(true)
s2 := strconv.FormatFloat(3.1415, 'E', -1, 64)
s3 := strconv.FormatInt(-2, 16)
s4 := strconv.FormatUint(2, 16)

其他

isPrint()

func IsPrint(r rune) bool

返回一个字符是否是可打印的,和unicode.IsPrint一样,r必须是:字母(广义)、数字、标点、符号、ASCII空格。

CanBackquote()

func CanBackquote(s string) bool

返回字符串s是否可以不被修改的表示为一个单行的、没有空格和tab之外控制字符的反引号字符串。

其他

除上文列出的函数外,strconv包中还有Append系列、Quote系列等函数。具体用法可查看官方文档。

推荐学习:Golang教程

The above is the detailed content of How to convert string to int type in go language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn