Package strconv
import "strconv"
func ParseFloat
func ParseFloat(s string, bitSize int) (float64, error)
ParseFloat converts the string s to a floating-point number with the
precision specified by bitSize: 32 for float32, or 64 for float64.
When bitSize=32, the result still has type float64, but it will be
convertible to float32 without changing its value.
If s is well-formed and near a valid floating point number, ParseFloat
returns the nearest floating point number rounded using IEEE754
unbiased rounding.
The errors that ParseFloat returns have concrete type *NumError and
include err.Num = s.
If s is not syntactically well-formed, ParseFloat returns err.Err =
ErrSyntax.
If s is syntactically well-formed but is more than 1/2 ULP away from
the largest floating point number of the given size, ParseFloat
returns f = ±Inf, err.Err = ErrRange.
Check the error from strconv.ParseFloat and check for an empty string
.
For example,
package main
import (
"fmt"
"strconv"
)
func main() {
for _, latitude := range []string{"40.7128", "gps", "neither", ""} {
fmt.Printf("Latitude: %q
", latitude)
if latitude != "gps" {
if _, err := strconv.ParseFloat(latitude, 10); err != nil || latitude == "" {
fmt.Printf("Incorrect option: %q
", latitude)
}
}
}
}
Playground: https://play.golang.org/p/4dNsMgRunFp
Output:
Latitude: "40.7128"
Latitude: "gps"
Latitude: "neither"
Incorrect option: "neither"
Latitude: ""
Incorrect option: ""