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")
}
}
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")
}
}
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")
}
}
You can use the math.Modf
function:
const epsilon = 1e-9 // Margin of error
if _, frac := math.Modf(math.Abs(a)); frac < epsilon || frac > 1.0 - epsilon {
// ...
}
epsilon
is necessary here since floating point math is not precise (e.g. float64(.3)+float64(.6)+float64(.1) != 1
)
From the godoc:
func Modf(f float64) (int float64, frac float64)
Modf returns integer and fractional floating-point numbers that sum to f. Both values have the same sign as f.
How about math.Trunc? It truncates a float64
to its whole-number component.
For example, something like:
if a.Trunc() == a {
// ...
}
Beware of the usual considerations about floating-point representation limitations. You might wish to check whether a.Trunc()
is within some small range of a
, to account for values like 1.00000000000000002
.
I solved it like so:
isWhole := int(value * 100) == int(value) * 100
Adjust the number of digits in the factor, e.g. multiply by 10000 to check 4 digits.
Just ceil or float your number and compare the result to origin value. The best solution for me:
var a float64 = 2.11
var b float64 = 3.00
fmt.Println(math.Ceil(a) == a) // 3.00 == 2.11; false; a is not a whole number
fmt.Println(math.Ceil(b) == b) // 3.00 == 3.00; true; b is a whole number
You can use a function:
func isWhole(x float64) bool {
return math.Ceil(x) == x
}
I think the following code might be useful,
func main(){
var (
a float64
b float64
c float64
)
a = 1.23
b = float64(int64(a))
c = a - b
if c > 0 {
fmt.Println("Not a Whole Number")
} else {
fmt.Println("Whole Number")
}
}