Determining Integer Values from Floating Point Numbers in Go
In Go, determining if a float64 represents a whole number can pose a challenge. The modulo operator (%) cannot be used directly on floats.
Solution 1: Comparing Float64 with Integer Equivalent
If your numbers can fit into an int64, consider comparing the float with its converted integer value:
if a == float64(int64(a)) { ... }
Solution 2: Utilizing math.Trunc
For the entire float64 domain, you can use the math.Trunc function:
if a == math.Trunc(a) { ... }
For example:
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") } }
This code correctly outputs "yay" when a is set to 2.00, indicating that it is a whole number.
The above is the detailed content of How Can I Check if a Go float64 Represents a Whole Number?. For more information, please follow other related articles on the PHP Chinese website!