Skip to content
DeveloperMemos

Getting Absolute Value in Kotlin with abs

Kotlin, Absolute Value, Programming1 min read

In mathematics, the absolute value of a number is its distance from zero, regardless of direction. In other words, it's the non-negative value of a number. In Kotlin, you can get the absolute value of a number using the abs function from the kotlin.math package.

Using abs in Kotlin

The abs function is a built-in function in Kotlin that returns the absolute value of the number. It can be used with different types of numbers such as Int, Double, Float, Long, and Short.

Here's how you can use it:

1import kotlin.math.abs
2
3fun main() {
4 val number = -42
5 val absolute = abs(number)
6 println("The absolute value of $number is $absolute")
7}

In this example, the abs function is used to get the absolute value of -42, which is 42.

Handling Complex Numbers

For complex numbers, you would need to calculate the magnitude (also known as the absolute value) differently. The magnitude of a complex number a + bi is sqrt(a*a + b*b). Unfortunately, Kotlin does not have built-in support for complex numbers, so you would need to implement this yourself.

Here's an example of how you can do it:

1import kotlin.math.sqrt
2
3data class Complex(val real: Double, val imaginary: Double) {
4 fun abs(): Double {
5 return sqrt(real * real + imaginary * imaginary)
6 }
7}
8
9fun main() {
10 val complexNumber = Complex(3.0, 4.0)
11 println("The absolute value of $complexNumber is ${complexNumber.abs()}")
12}

In this example, a Complex data class is created with a custom abs function to calculate the magnitude of the complex number.


The abs function in Kotlin is a useful function for getting the absolute value of a number. It's easy to use and works with different types of numbers. For complex numbers, you would need to implement the calculation yourself, but it's still fairly straightforward.