Scala Tutorial Scala References

Scala - Math round() Method



The Scala Math round() method returns the value of argument rounded to its nearest integer. The method can be overloaded and it can take Float and Double arguments. In special cases it returns the following:

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Int.MinValue or Long.MinValue, the result is equal to the value of Integer.MinValue or Long.MinValue.
  • If the argument is positive infinity or any value greater than or equal to the value of Int.MaxValue or Long.MaxValue, the result is equal to the value of Integer.MaxValue or Long.MaxValue.

Syntax

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

Parameters

x Specify a floating point value to be rounded.

Return Value

Returns the value of argument rounded to its nearest integer.

Exception

NA.

Example:

In the example below, round() method returns the value of argument rounded to its nearest integer.

import scala.math._

object MainObject {
  def main(args: Array[String]) {
    println(s"round(-10.3) = ${round(-10.3)}");
    println(s"round(-10.5) = ${round(-10.5)}");
    println(s"round(-10.7) = ${round(-10.7)}"); 
    println(s"round(5.3) = ${round(5.3)}"); 
    println(s"round(5.5) = ${round(5.5)}");
    println(s"round(5.7) = ${round(5.7)}");
    println(s"round(0.0) = ${round(0.0)}"); 
    println(s"round(Double.NaN) = ${round(Double.NaN)}");
    println("round(Double.PositiveInfinity) = "
            + round(Double.PositiveInfinity));
    println("round(Double.NegativeInfinity) = "
            + round(Double.NegativeInfinity));
  }
}

The output of the above code will be:

round(-10.3) = -10
round(-10.5) = -10
round(-10.7) = -11
round(5.3) = 5
round(5.5) = 6
round(5.7) = 6
round(0.0) = 0
round(Double.NaN) = 0
round(Double.PositiveInfinity) = 9223372036854775807
round(Double.NegativeInfinity) = -9223372036854775808

❮ Scala - Math Methods

5