Search code examples
androidkotlinif-statementintegernumbers

check if a number is decimal or integer in kotlin


I would like to know how I can identify a number as decimal or integer, I was already researching how to do it but I run into some problems when using it in an if else conditional, it gives me the following error:

Operator '==' cannot be applied to 'Float' and 'Int'.

When requesting the data from the user, I save it as Float and when placing it in the conditional it generates that error. Does anyone know how I can request a number and then check if it is integer or has decimal? By the way I am using kotlin

Code:

fun main(){
 val number01 = readLine()!!.toFloat()

 if (number01 % 1 == 0){ // A X + B = 0
        println("Solution 1: $number01")
    }else{
        println("Solution 2: $number01")
    } 
}

I already looked on the internet how to know if it is an integer or if it is a number with decimal but when using it in a conditional it generates an error.


Solution

  • the output from number01%1 is Float and your using == to a Int .To correct that you have to change your code into:

    fun main(){
     val number01 = readLine()!!.toFloat()
    
     if (number01 % 1 == 0f){ 
            println("Solution 1: $number01")
        }else{
            println("Solution 2: $number01")
        } 
    }