Go数字解析实例

从字符串解析数字是许多程序中的一个基本但常见的任务; 这里是演示如何在Go编程中使用。内置包strconv提供数字解析。

可参考示例中的代码 -

所有的示例代码,都放在 F:\worksp\golang 目录下。安装Go编程环境请参考:/tutorial/detail-5562.html

number-parsing.go的完整代码如下所示 -

package main

// The built-in package `strconv` provides the number
// parsing.
import "strconv"
import "fmt"

func main() {

    // With `ParseFloat`, this `64` tells how many bits of
    // precision to parse.
    f, _ := strconv.ParseFloat("1.234", 64)
    fmt.Println(f)

    // For `ParseInt`, the `0` means infer the base from
    // the string. `64` requires that the result fit in 64
    // bits.
    i, _ := strconv.ParseInt("123", 0, 64)
    fmt.Println(i)

    // `ParseInt` will recognize hex-formatted numbers.
    d, _ := strconv.ParseInt("0x1c8", 0, 64)
    fmt.Println(d)

    // A `ParseUint` is also available.
    u, _ := strconv.ParseUint("789", 0, 64)
    fmt.Println(u)

    // `Atoi` is a convenience function for basic base-10
    // `int` parsing.
    k, _ := strconv.Atoi("135")
    fmt.Println(k)

    // Parse functions return an error on bad input.
    _, e := strconv.Atoi("wat")
    fmt.Println(e)
}

执行上面代码,将得到以下输出结果 -

F:\worksp\golang>go run number-parsing.go
1.234


135
strconv.ParseInt: parsing "wat": invalid syntax

上一篇:Go随机数实例

下一篇:Go URL解析实例

关注微信小程序
程序员编程王-随时随地学编程

扫描二维码
程序员编程王

扫一扫关注最新编程教程