Thursday, December 30, 2010

Rounding off in Java - Round two decimal places

public class RoundTwoDecimalPlaces{
public static void main(String[] args) {
float num = 2.954165f;
float round = Round(num,2);
System.out.println("Rounded data: " + round);
}

public static float Round(float Rval, int Rpl) {
float p = (float)Math.pow(10,Rpl);
Rval = Rval * p;
float tmp = Math.round(Rval);
return (float)tmp/p;
}

public static double Round(double Rval, int Rpl) {
double p = (double) Math.pow(10, Rpl);
Rval = Rval * p;

//double tmp = Math.round(Rval);
double tmp = Math.floor(Rval);

return (double) tmp / p;
}

}

No comments:

Post a Comment