如何测试一个浮点数是否是Go中的整数? [英] How to test whether a float is a whole number in Go?

查看:828
本文介绍了如何测试一个浮点数是否是Go中的整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我原本试过这个,但%运算符没有为float64定义。

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")
    }
}


推荐答案

假设你的数字符合 int64 ,你可以比较float值和转换后的整数值,看它们是否相同:

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")
}

否则你可以使用 math.Trunc 函数详细的 here ,如下所示:

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")
}

这应该在整个 float64 域中工作。

That one should work within the entire float64 domain.

这篇关于如何测试一个浮点数是否是Go中的整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆