Java Math Round() - Programiz
Maybe your like
The round() method rounds the specified value to the closest int or long value and returns it. That is, 3.87 is rounded to 4 and 3.24 is rounded to 3.
Example
class Main { public static void main(String[] args) { double a = 3.87; System.out.println(Math.round(a)); } } // Output: 4Syntax of Math.round()
The syntax of the round() method is:
Math.round(value)Here, round() is a static method. Hence, we are accessing the method using the class name, Math.
round() Parameters
The round() method takes a single parameter.
- value - number which is to be rounded
Note: The data type of the value should be either float or double.
round() Return Value
- returns the int value if the argument is float
- returns the long value if the argument is double
The round() method:
- rounds upward if the value after the decimal is greater than or equal to 5 1.5 => 2 1.7 => 2
- rounds downward if the value after the decimal is smaller than 5 1.3 => 1
Example 1: Java Math.round() with double
class Main { public static void main(String[] args) { // Math.round() method // value greater than 5 after decimal double a = 1.878; System.out.println(Math.round(a)); // 2 // value equals to 5 after decimal double b = 1.5; System.out.println(Math.round(b)); // 2 // value less than 5 after decimal double c = 1.34; System.out.println(Math.round(c)); // 1 } }Example 2: Java Math.round() with float
class Main { public static void main(String[] args) { // Math.round() method // value greater than 5 after decimal float a = 3.78f; System.out.println(Math.round(a)); // 4 // value equals to 5 after decimal float b = 3.5f; System.out.println(Math.round(b)); // 4 // value less than 5 after decimal float c = 3.44f; System.out.println(Math.round(c)); // 3 } }Also Read:
- Java Math.floor()
- Java Math.ceil()
Tag » How To Roundup In Java
-
How To Round Up In Java Code Example
-
Rounding Of Numbers In Java - Vertex Academy
-
Java Round Up Any Number - Math - Stack Overflow
-
How To Round Up In Java - Linux Hint
-
Round Up A Number In Java | Delft Stack
-
How To Round A Number To N Decimal Places In Java - Baeldung
-
How To Use The Java Math.round() Method
-
Java - Round() Method - Tutorialspoint
-
Java Math Round() Method With Example - GeeksforGeeks
-
Java Math.round() Method With Examples - Javatpoint
-
How To Round Up To 2 Decimal Places In Java? - Intellipaat Community
-
Java Math.round() - Scaler Topics
-
How Do I Round A Decimal To Nearest Integer In Java? - Quora
-
Java - How To Round Double / Float Value To 2 Decimal Places