Number Parsing {.en}

数字解析 {.zh}

::: {.en} Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Go. :::

::: {.zh}

从字符串中解析数字是许多程序中基本但常见的任务;这是在Go中如何做到的。

:::

  1. package main

::: {.en} The built-in package strconv provides the number parsing. :::

::: {.zh}

内置包strconv提供了numberparsing。

:::

  1. import "strconv"
  2. import "fmt"
  3. func main() {

::: {.en} With ParseFloat, this 64 tells how many bits of precision to parse. :::

::: {.zh}

使用ParseFloat,这个64表示要解析的精确位数。

:::

  1. f, _ := strconv.ParseFloat("1.234", 64)
  2. fmt.Println(f)

::: {.en} For ParseInt, the 0 means infer the base from the string. 64 requires that the result fit in 64 bits. :::

::: {.zh}

对于ParseInt,“0”表示从字符串推断出基数。 64要求结果适合64位。

:::

  1. i, _ := strconv.ParseInt("123", 0, 64)
  2. fmt.Println(i)

::: {.en} ParseInt will recognize hex-formatted numbers. :::

::: {.zh}

ParseInt将识别十六进制格式的数字。

:::

  1. d, _ := strconv.ParseInt("0x1c8", 0, 64)
  2. fmt.Println(d)

::: {.en} A ParseUint is also available. :::

::: {.zh}

还可以使用ParseUint

:::

  1. u, _ := strconv.ParseUint("789", 0, 64)
  2. fmt.Println(u)

::: {.en} Atoi is a convenience function for basic base-10 int parsing. :::

::: {.zh}

Atoi是基本的10int解析的便利函数。

:::

  1. k, _ := strconv.Atoi("135")
  2. fmt.Println(k)

::: {.en} Parse functions return an error on bad input. :::

::: {.zh}

解析函数在输入错误时返回错误。

:::

  1. _, e := strconv.Atoi("wat")
  2. fmt.Println(e)
  3. }
  1. $ go run number-parsing.go
  2. 1.234
  3. 123
  4. 456
  5. 789
  6. 135
  7. strconv.ParseInt: parsing "wat": invalid syntax

::: {.en} Next we’ll look at another common parsing task: URLs. :::

::: {.zh}

接下来我们将看另一个常见的解析任务:URL。

:::