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 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据