number parsing example

This commit is contained in:
Mark McGranaghan 2012-09-20 20:10:56 -07:00
parent 6f45d7d219
commit 5e39ab34db
2 changed files with 34 additions and 20 deletions

34
src/xx-number-parsing.go Normal file
View File

@ -0,0 +1,34 @@
// Number parsing
package main
import (
"fmt"
"strconv" // Package `strconv` provides number parsing.
)
func main() {
f, _ := strconv.ParseFloat("1.234", 64) // `64` tells how many bits of precision to parse.
fmt.Println(f)
i, _ := strconv.ParseInt("123", 0, 64) // `0` means infer the base from the string.
println(i) // `64` requires that the result fit in 64 bits.
d, _ := strconv.ParseInt("0x1b3e", 0, 64) // `ParseInt` will recognize hex-formatted numbers.
println(d)
k, _ := strconv.Atoi("456") // `Atoi` is a convenienice function for `int` parsing.
println(k)
_, e := strconv.Atoi("wat") // Parse functions return an error on bad input.
fmt.Println(e)
}
/*
$ go run xx-number-parsing.go
1.234
123
6974
456
strconv.ParseInt: parsing "wat": invalid syntax
*/

View File

@ -1,20 +0,0 @@
package main
import ("fmt"; "strconv")
func main() {
b, _ := strconv.ParseBool("true")
fmt.Println(b)
f, _ := strconv.ParseFloat("1.234", 64)
fmt.Println(f)
i, _ := strconv.ParseInt("123", 0, 64)
fmt.Println(i)
d, _ := strconv.ParseInt("0x1b3e", 0, 64)
fmt.Println(d)
k, _ := strconv.Atoi("456")
fmt.Println(k)
}