Golang 中的数字解析

go programmingserver side programmingprogramming

Go 中的数字解析是将 字符串 形式的数字转换为 数字 形式。我们所说的数字形式是指这些数字可以转换为整数、浮点数等。

最广泛使用的解析数字的包是 Go 库提供的"strconv"包。Go 中的数字解析有很多种情况,我们将在本文中逐一讨论。

最基本的方法是,当我们有一个十进制数字,它实际上是一个字符串形式,我们想将其转换为整数。为了实现这一点,我们可以使用最广泛使用的 Atoi() 函数。

Atoi() 函数的语法如下所示。

result, error := strconv.Atoi(String)

现在,假设我们有一个包含值"191"的字符串,我们想将其转换为整数。

示例

请考虑以下代码。

package main
import (
   "fmt"
   "strconv"
)
func main() {
   var value string = "123"
   res, err := strconv.Atoi(value)
   if err != nil {
      fmt.Println("Error encountered:", err)
      return
   }
   fmt.Println("The number now is:", res)
   fmt.Printf("The type of the number is: %T", res)
}

输出

如果我们使用命令 go run main.go 运行代码,那么我们将在终端中看到以下输出。

The number now is: 123
The type of the number is: int

现在,第二种最常见的数字解析是当我们想要将字符串形式的数字转换为 64 位数字时。为此,我们可以使用 ParseInt()ParseFloat() 函数,它们都位于 strconv 函数内部。

我们来看一下这两个函数的示例,其中一个函数用于解析浮点数,另一个函数用于传递 64 位整数值。

ParseInt() 的语法

number, error := strconv.ParseInt(string, base, bitSize)

ParseFloat() 的语法

number, error := strconv.ParseFloat(string, bitSize)

示例 2

在本例中,我们将同时使用这两个函数ParseInt()ParseFloat() 函数。

package main
import (
   "fmt"
   "strconv"
)
func main() {
   var value string = "123"
   var value1 string = "1.23"
   res, err := strconv.ParseInt(value, 0, 64)
   if err != nil {
      fmt.Println("Error encountered:", err)
      return
   }
   fmt.Println("The number now is:", res)
   fmt.Printf("The type of the number is: %T \n", res)
   res1, err1 := strconv.ParseFloat(value1, 64)
   if err1 != nil {
      fmt.Println("Error encountered:", err1)
      return
   }
   fmt.Println("The number now is:", res1)
   fmt.Printf("The type of the number is: %T", res1)
}

输出

如果我们使用命令 go run main.go 运行代码,那么我们将在终端中看到以下输出。

The number now is: 123
The type of the number is: int64
The number now is: 1.23
The type of the number is: float64

关于 ParseInt() 函数,需要注意的一点是它也能识别十六进制格式的数字。

假设我们有一个十六进制数"0x1F3",它以字符串形式存在,我们想将其转换为整数。为此,我们只能使用 ParseInt() 函数。

示例 3

请考虑下面的代码。

package main
import (
   "fmt"
   "strconv"
)
func main() {
   var value string = "0x1F3"
   res, err := strconv.ParseInt(value, 0, 64)
   if err != nil {
      fmt.Println("Error encountered:", err)
      return
   }
   fmt.Println("The number now is:", res)
   fmt.Printf("The type of the number is: %T \n", res)
}

输出

如果我们使用命令 go run main.go 运行代码,那么我们将在终端中看到以下输出。

The number now is: 499
The type of the number is: int64

相关文章