What is a method to check if the output of a calculation is a whole number? I've tried doing this:
if ((i / 3) is Int ) {
print("Whole Number")
}
But it seems to be checking the type of the variable, not what the output is.
Edit: Apparently if the variable is an integer, it automatically rounds the output of the operation, so I had to do something like this:
if((i.toFloat()/3) == (i / 3).toFloat()){
println("Whole Number")
An easy way to check whether a / b is a whole number is to check the remainder for being zero: a % b == 0.
Note, however, that if both operands of / are of an integral type (Short, Int, Long), then the division result is always an integer number (the fractional part is just dropped), so, if you have a val i: Int = 2 then i % 3 == 1 but i / 3 == 0. To use fractional division, make at least one of the operands fractional like i / 3.0 or i.toDouble / 3.
In case you want to check that a Double is whole, you can use d % 1.0 == 0.0 or check that Math.floor(d) == d.
A simple trick is to check if the values of ceil and floor functions are equal or not
If they are equal, the result is a whole number
if not, the result is not a whole number
if (ceil(i/3) == floor(i/3)) {
print("int (a whole number)")
} else {
print("not int (not a whole number)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With