publish number-parsing
This commit is contained in:
parent
27f79cd6cb
commit
f8ed65b151
@ -52,8 +52,8 @@ Defer
|
||||
# Epochs
|
||||
# Elapsed Time
|
||||
# Random Numbers
|
||||
# Number Parsing
|
||||
URLs
|
||||
Number Parsing
|
||||
URL Parsing
|
||||
SHA1 Hashes
|
||||
Base64 Encoding
|
||||
# Reading Files
|
||||
|
@ -1,29 +1,42 @@
|
||||
// Parsing numbers from strings is a basic but common task
|
||||
// in many programs; here's how to do it in Go.
|
||||
|
||||
package main
|
||||
|
||||
// Package `strconv` provides the number parsing.
|
||||
// The built-in package `strconv` provides the number
|
||||
// parsing.
|
||||
import "strconv"
|
||||
import "fmt"
|
||||
|
||||
func main() {
|
||||
// `64` tells how many bits of precision to parse.
|
||||
|
||||
// With `ParseFloat`, this `64` tells how many bits of
|
||||
// precision to parse.
|
||||
f, _ := strconv.ParseFloat("1.234", 64)
|
||||
fmt.Println(f)
|
||||
|
||||
// `0` means infer the base from the string.
|
||||
// `64` requires that the result fit in 64 bits.
|
||||
// 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)
|
||||
println(i)
|
||||
fmt.Println(i)
|
||||
|
||||
// `ParseInt` will recognize hex-formatted numbers.
|
||||
d, _ := strconv.ParseInt("0x1b3e", 0, 64)
|
||||
println(d)
|
||||
d, _ := strconv.ParseInt("0x1c8", 0, 64)
|
||||
fmt.Println(d)
|
||||
|
||||
// `Atoi` is a convenienice function for `int`
|
||||
// parsing.
|
||||
k, _ := strconv.Atoi("456")
|
||||
println(k)
|
||||
// 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)
|
||||
}
|
||||
|
||||
// Next we'll look at another common parsing task: URLs.
|
||||
|
@ -1,6 +1,7 @@
|
||||
$ go run xx-number-parsing.go
|
||||
$ go run number-parsing.go
|
||||
1.234
|
||||
123
|
||||
6974
|
||||
456
|
||||
789
|
||||
135
|
||||
strconv.ParseInt: parsing "wat": invalid syntax
|
||||
|
@ -1,6 +1,6 @@
|
||||
# Running our URL parsing program shows all the different
|
||||
# pieces that we extracted.
|
||||
$ go run urls.go
|
||||
$ go run url-parsing.go
|
||||
postgres
|
||||
user:pass
|
||||
user
|
Loading…
x
Reference in New Issue
Block a user