Popular Tutorials
Start Learning JavaCertification Courses
Created with over a decade of experience and thousands of feedback.
Python online compiler
JavaScript online compiler
SQL online compiler
Java online compiler
HTML online compiler
C online compiler
C++ online compiler
C# online compiler
PHP online compiler
Swift online compiler
Kotlin online compiler
TypeScript online compiler
Go online compiler
Rust online compiler
Scala online compiler
Dart online compiler
R online compiler
Ruby online compiler
Java Math round()
In this tutorial, we will learn about the Java Math.round() method with the help of examples.
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: 4
Syntax 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
intvalue if the argument isfloat - returns the
longvalue if the argument isdouble
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:
Did you find this article helpful?