Below is a Java Program containing a method round” to Round an Input Double Number to 2 Decimal Places. The same logic can be used for numbers of other Data Types. We can make use of 3 Built-in methods of the Math Function to achieve this.
[sourcecode language='java']
/*
public class JavaRoundingDemo {
private static double PI = 3.14159;
public static void main(String[] args) {
double piAfterRounding = round(PI, 2); //Rounding to 2 Decimal Places
System.out.println(”Simple Rounding Yeilds: ” + Math.round(PI));
System.out.println(”Rounded to 2 Decimal Places: ” + piAfterRounding);
}
public static double round(double input, int roundFactor) {
double p1 = (double) Math.pow(10, roundFactor); // Results in (100)
input = input * p1; // Results in 314.159
double temp = Math.round(input); // Results in 314.16
return temp / p1;
}
}
[/sourcecode]











Leave a Reply