Scala Tutorial Scala References

Scala - Math abs() Method



The Scala Math abs() method returns the absolute value (positive value) of the specified number. The method can be overloaded and it can take Int, Double, Float and Long arguments. In special cases it returns the following:

  • If the argument is positive or negative infinity, the result is Infinity.
  • If the argument is NaN, the result is NaN.
  • If the argument is equal to the value of Int.MinValue or Long.MinValue, the most negative representable Int value or Long value, the result is that same value, which is negative.

Syntax

def abs(x: Int): Int = java.lang.Math.abs(x)
def abs(x: Long): Long = java.lang.Math.abs(x)
def abs(x: Float): Float = java.lang.Math.abs(x)
def abs(x: Double): Double = java.lang.Math.abs(x)

Parameters

x Specify a number whose absolute value need to be determined.

Return Value

Returns the absolute value (positive value) of the argument.

Exception

NA.

Example:

In the example below, abs() method returns the absolute value (positive value) of the specified number.

import scala.math._

object MainObject {
  def main(args: Array[String]) {
    println(s"abs(-10) = ${abs(-10)}");   
    println(s"abs(5.5) = ${abs(5.5)}"); 
    println(s"abs(Double.NaN) = ${abs(Double.NaN)}");  
    println(s"abs(Int.MinValue) = ${abs(Int.MinValue)}"); 
    println(s"abs(Long.MinValue) = ${abs(Long.MinValue)}"); 
    println("abs(Double.PositiveInfinity) = "
            + abs(Double.PositiveInfinity));
    println("abs(Double.NegativeInfinity) = "
            + abs(Double.NegativeInfinity));
  }
}

The output of the above code will be:

abs(-10) = 10
abs(5.5) = 5.5
abs(Double.NaN) = NaN
abs(Int.MinValue) = -2147483648
abs(Long.MinValue) = -9223372036854775808
abs(Double.PositiveInfinity) = Infinity
abs(Double.NegativeInfinity) = Infinity

❮ Scala - Math Methods