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

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)