Kotlin Program to Check Whether a Number is Positive or Negative

In this program, you'll learn to check if a given number is positive or negative. This is done by using an if-else statement or a when expression in Kotlin.

To check whether a number is positive or negative, you compare it with 0.

  • If a number is greater than zero, it is a positive number.
  • If a number is less than zero, it is a negative number.
  • If a number equals to zero, it is zero.

Example 1: Check if a Number is Positive or Negative using if else statement

fun main(args: Array<String>) {

    val number = 12.3

    if (number < 0.0)
        println("$number is a negative number.")
    else if (number > 0.0)
        println("$number is a positive number.")
    else
        println("$number is 0.")
}

When you run the program, the output will be:

12.3 is a positive number.

Here's the equivalent Java code: Java Program to Check if a Number is Positve or Negative.


if else statement in the above program can also be replaced using a when expression.

Example 2: Check if a Number is Positive or Negative using when expression

fun main(args: Array<String>) {

    val number = -12.3

    when {
        number < 0.0 -> println("$number is a negative number.")
        number > 0.0 -> println("$number is a positive number.")
        else -> println("$number is 0.")
    }
}

When you run the program, the output will be:

-12.3 is a negative number.