dongshai8330
2013-05-14 03:51
浏览 1.1k
已采纳

如何在Go中测试浮点数是否为整数?

I originally tried this, however the % operator isn't defined for float64.

func main(){
    var a float64
    a = 1.23
    if a%1 == 0{
        fmt.Println("yay")
    }else{
        fmt.Println("you fail")
    }
}

图片转代码服务由CSDN问答提供 功能建议

我最初尝试过此操作,但是未为float64定义%运算符。

  func main(){
 var a float64 
a = 1.23 
如果a%1 == 0 {
 fmt.Println(“ yay”)
}否则{
 fmt.Println  (“失败”)
} 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • dsjbest2014 2013-05-14 04:01
    已采纳

    Assuming your numbers will fit into an int64, you can just compare the float value with a converted integer value to see if they're the same:

    if a == float64(int64(a)) {
        fmt.Println("yay")
    } else {
        fmt.Println("you fail")
    }
    

    Otherwise you can use the math.Trunc function detailed here, with something like:

    if a == math.Trunc(a) {
        fmt.Println("yay")
    } else {
        fmt.Println("you fail")
    }
    

    That one should work within the entire float64 domain.

    已采纳该答案
    打赏 评论
  • doujia2463 2013-05-14 04:06

    I think the following code might be useful,

    func main(){
        var (
              a float64
              b float64
              c float64
        ) 
        a = 1.23
        b = float64(int64(a))
        c = a - b
        if c > 0 {
            fmt.Println("Not a Whole Number")
        } else {
            fmt.Println("Whole Number")
        }
    }
    
    1 打赏 评论
  • doudou3213 2013-05-14 04:01

    How about math.Trunc? It truncates a float64 to its whole-number component.

    For example, something like:

    if a.Trunc() == a {
        // ...
    }
    

    Beware of the usual considerations about floating-point representation limitations. You might wish to check whether a.Trunc() is within some small range of a, to account for values like 1.00000000000000002.

    打赏 评论
  • doumen9709 2016-02-02 21:21

    You can use the math.Modf function:

    const epsilon = 1e-9 // Margin of error
    if _, frac := math.Modf(math.Abs(a)); frac < epsilon || frac > 1.0 - epsilon {
        // ...
    }
    

    epsilon is necessary here since floating point math is not precise (e.g. float64(.3)+float64(.6)+float64(.1) != 1)

    From the godoc:

    func Modf(f float64) (int float64, frac float64)
    

    Modf returns integer and fractional floating-point numbers that sum to f. Both values have the same sign as f.

    打赏 评论
  • douxun7992 2018-12-12 19:57

    I solved it like so:

    isWhole := int(value * 100) == int(value) * 100
    

    Adjust the number of digits in the factor, e.g. multiply by 10000 to check 4 digits.

    打赏 评论

相关推荐 更多相似问题