Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go数字解析实例
Go数字解析实例
作者:--    发布时间:2019-11-20

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

可参考示例中的代码 -

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.com/go/go_environment.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
123
456
789
135
strconv.parseint: parsing "wat": invalid syntax

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册