search
HomeBackend DevelopmentGolangHow to convert string to int type in go language
How to convert string to int type in go languageMar 15, 2021 pm 02:00 PM
go languagetype conversion

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
go语言有没有缩进go语言有没有缩进Dec 01, 2022 pm 06:54 PM

go语言有缩进。在go语言中,缩进直接使用gofmt工具格式化即可(gofmt使用tab进行缩进);gofmt工具会以标准样式的缩进和垂直对齐方式对源代码进行格式化,甚至必要情况下注释也会重新格式化。

go语言为什么叫gogo语言为什么叫goNov 28, 2022 pm 06:19 PM

go语言叫go的原因:想表达这门语言的运行速度、开发速度、学习速度(develop)都像gopher一样快。gopher是一种生活在加拿大的小动物,go的吉祥物就是这个小动物,它的中文名叫做囊地鼠,它们最大的特点就是挖洞速度特别快,当然可能不止是挖洞啦。

一文详解Go中的并发【20 张动图演示】一文详解Go中的并发【20 张动图演示】Sep 08, 2022 am 10:48 AM

Go语言中各种并发模式看起来是怎样的?下面本篇文章就通过20 张动图为你演示 Go 并发,希望对大家有所帮助!

【整理分享】一些GO面试题(附答案解析)【整理分享】一些GO面试题(附答案解析)Oct 25, 2022 am 10:45 AM

本篇文章给大家整理分享一些GO面试题集锦快答,希望对大家有所帮助!

tidb是go语言么tidb是go语言么Dec 02, 2022 pm 06:24 PM

是,TiDB采用go语言编写。TiDB是一个分布式NewSQL数据库;它支持水平弹性扩展、ACID事务、标准SQL、MySQL语法和MySQL协议,具有数据强一致的高可用特性。TiDB架构中的PD储存了集群的元信息,如key在哪个TiKV节点;PD还负责集群的负载均衡以及数据分片等。PD通过内嵌etcd来支持数据分布和容错;PD采用go语言编写。

go语言是否需要编译go语言是否需要编译Dec 01, 2022 pm 07:06 PM

go语言需要编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言,也就说Go语言程序在运行之前需要通过编译器生成二进制机器码(二进制的可执行文件),随后二进制文件才能在目标机器上运行。

go语言能不能编译go语言能不能编译Dec 09, 2022 pm 06:20 PM

go语言能编译。Go语言是编译型的静态语言,是一门需要编译才能运行的编程语言。对Go语言程序进行编译的命令有两种:1、“go build”命令,可以将Go语言程序代码编译成二进制的可执行文件,但该二进制文件需要手动运行;2、“go run”命令,会在编译后直接运行Go语言程序,编译过程中会产生一个临时文件,但不会生成可执行文件。

golang map怎么删除元素golang map怎么删除元素Dec 08, 2022 pm 06:26 PM

删除map元素的两种方法:1、使用delete()函数从map中删除指定键值对,语法“delete(map, 键名)”;2、重新创建一个新的map对象,可以清空map中的所有元素,语法“var mapname map[keytype]valuetype”。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),