In Java, Math.round() function is used to print the values up to two decimal places. In this blog, we will learn different methods to print the values up to 2 decimal places in Java. Let’s learn those methods in detail.
Table of Contents:
Different Methods to Round Numbers in Java
Method 1: Using Math.round() function
We can use Math.round() function to print the value up to 2 values in Java. To use the round function, we should multiply the num by 100.0 and then divide by 100.0. This function is easy to use and mostly used by developers to round off a decimal value.
Let’s see an example:
Code to use Math.round():
public class Main {
public static void main(String[] args) {
double num = 3.14159;
double intellipaat= Math.round(num * 100.0) / 100.0;
System.out.println(intellipaat);
}
}
Output:
3.14
Explanation: Here, we have rounded the values to 2 digits.
We can also use the String.format() function to round off the number up to 2 digits. This method returns it in string, so if we want to the integer value, we have to convert it using Double.parseDouble(). Let’s learn this with an example:
public class Main {
public static void main(String[] args) {
double number = 3.14159;
String intellipaat = String.format("%.2f", number);
System.out.println(intellipaat);
}
}
Output:
3.14
Explanation: Here, %.2f is used to print the value up to 2 digits.
Method 3: Using Math.ceil() function
We can also use Math.ceil() function to print the values up to 2 digits. ceil() will round off the digit to its next higher digit. This function always returns a value that is nearly rounded off.
Code to use Math.ceil():
public class Main {
public static void main(String[] args) {
double number = 3.14159;
double intellipaat= Math.ceil(number * 100.0) / 100.0;
System.out.println(intellipaat); }
}
Output: 3.15
Explanation: Here we will round off the current digit to its next higher digit, so After 3.14 it will become 3.15.
Conclusion
Java is an object-oriented programming language, that is in high demand these days.
In this article, we have learned different approaches to round off the number up to 2 digits in Java. If you want to excel in your career in Java, you must visit our Java Course.
FAQs
Can I use String.format for rounding?
Yes, but it returns a String, not a double:
What is round() in Java?
The Math.round() method rounds a floating-point number to the nearest whole number (long or int). For two decimal places, multiply by 100, round, and divide by 100.
Can I learn Java in 21 days?
Yes, you can learn Java basics in 21 days with consistent practice.
What is Java used for?
Java is used for building web applications, mobile apps (Android), enterprise software, game development, and backend systems.