diff --git a/src/xx-number-parsing.go b/src/xx-number-parsing.go new file mode 100644 index 0000000..6233d88 --- /dev/null +++ b/src/xx-number-parsing.go @@ -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 +*/ diff --git a/src/xx-parse.go b/src/xx-parse.go deleted file mode 100644 index 1a5216b..0000000 --- a/src/xx-parse.go +++ /dev/null @@ -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) -}