Math
9 methodsThe Math class contains methods for performing basic numeric operations.
static int abs(int a)Return the absolute value of an int. Long.MIN_VALUE remains negative.
Parameters
| Name | Type | Description |
|---|---|---|
| a | int | Argument. |
Returns
int
Example
Math.abs(-5) // 5
Math.abs(5) // 5
Math.abs(-2147483648) // -2147483648 (overflow!)static int max(int a, int b)Return the greater of two int values.
Parameters
| Name | Type | Description |
|---|---|---|
| a | int | First value. |
| b | int | Second value. |
Returns
int
Example
Math.max(3, 7) // 7
Math.max(-1, -5) // -1static int min(int a, int b)Return the smaller of two int values.
Parameters
| Name | Type | Description |
|---|---|---|
| a | int | First value. |
| b | int | Second value. |
Returns
int
Example
Math.min(3, 7) // 3
Math.min(-1, -5) // -5static double pow(double a, double b)Return the value of a raised to the power of b.
Parameters
| Name | Type | Description |
|---|---|---|
| a | double | Base. |
| b | double | Exponent. |
Returns
double
Example
Math.pow(2, 10) // 1024.0
Math.pow(9, 0.5) // 3.0
Math.pow(2, -1) // 0.5static double sqrt(double a)Return the correctly rounded positive square root of a. NaN if a < 0.
Parameters
| Name | Type | Description |
|---|---|---|
| a | double | Value. |
Returns
double
Example
Math.sqrt(9) // 3.0
Math.sqrt(2) // 1.4142135623730951
Math.sqrt(-1) // NaNstatic long round(double a)Return the closest long to a, with ties rounding to positive infinity.
Parameters
| Name | Type | Description |
|---|---|---|
| a | double | Value to round. |
Returns
long
Example
Math.round(2.4) // 2
Math.round(2.5) // 3
Math.round(-2.5) // -2static double ceil(double a)Return the smallest (closest to negative infinity) double that is greater than or equal to a and equal to a mathematical integer.
Parameters
| Name | Type | Description |
|---|---|---|
| a | double | Value. |
Returns
double
Example
Math.ceil(2.1) // 3.0
Math.ceil(-2.9) // -2.0static double floor(double a)Return the largest (closest to positive infinity) double that is less than or equal to a and equal to a mathematical integer.
Parameters
| Name | Type | Description |
|---|---|---|
| a | double | Value. |
Returns
double
Example
Math.floor(2.9) // 2.0
Math.floor(-2.1) // -3.0static double random()Return a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.
Returns
double
Example
Math.random() // e.g. 0.5819...
(int)(Math.random() * 6) + 1 // 1..6 (dice)
Math.random() * 100 // 0..99.99...