gomodulus

How to test whether a float is a whole number in 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")
    }
}

Solution

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

    if a == float64(int64(a)) { ... }
    

    Alternatively, if you need the entire float64 domain, you can use the math.Trunc function, with something like:

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

    For example, the following code correctly outputs yay, on testing over at the Go playground:

    package main
    
    import (
        "fmt"
        "math"
    )
    
    func main() {
        var a float64 = 2.00
        if a == math.Trunc(a) {
            fmt.Println("yay")
        } else {
            fmt.Println("you fail")
        }
    }