从字符串解析数字是许多程序中的一个基本但常见的任务; 这里是演示如何在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