donglu1971 2018-07-11 16:26
浏览 12
已采纳

如何检查值是否为浮点数[关闭]

I want to check whether a value that I get passed is a float number. I have a piece of code that checks whether it is a certain string, or a float number. If neither, then give an error. Here is the code:

if sensorData.Passport.Geolocation.Latitude != "gps" && sensorData.Passport.Geolocation.Latitude != "internet" && sensorData.Passport.Geolocation.Latitude != "unknown" && sensorData.Passport.Geolocation.Latitude != //a float nmber{
            fmt.Println("Incorrect option")
        }

How do I check whether the data is a float number?

  • 写回答

1条回答 默认 最新

  • doumo6356 2018-07-11 16:30
    关注

    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: ""
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗