How to test whether a float is a whole number in Go?

John Calder picture John Calder · May 14, 2013 · Viewed 12.1k times · Source

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

Answer

paxdiablo picture paxdiablo · May 14, 2013

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.