Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if the output of a calculation is a whole number

Tags:

kotlin

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")
like image 204
tplc10 Avatar asked Jul 31 '17 17:07

tplc10


2 Answers

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.

like image 200
hotkey Avatar answered Sep 20 '22 13:09

hotkey


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)")
}
like image 35
Mohamed Medhat Avatar answered Sep 17 '22 13:09

Mohamed Medhat