How to create a code in java?

Write an expression (or several expressions) that will round the variable x to 2 decimal places. It should work for any value that is stored in x. This should not produce a String, it must produce an actual double value! Just printing out the rounded value is not enough, the rounded value must be stored back in a double variable.


For example:

double x = 123.25032;
double z = [YOUR EXPRESSION HERE]

Your expression should result in z == 123.25.


If x = 52.118907, then z == 52.12.

If x = 9.4512, then z == 9.45.

If x = 9.455, then z == 9.46.

Eaf F2010-11-07T21:34:20Z

Favorite Answer

import java.text.DecimalFormat;

class Carl {

public static void main(String[] carl){
DecimalFormat dd = new DecimalFormat("#.##");
double d = 1.2345;
System.out.println(dd.format(d));
}


}

Linkdead2010-11-08T05:33:13Z

I was kind of wondering about that myself, because Math.round doesn't let you specify decimal digits, it just always gives you the whole number portion

here's *a* way to do it, it's kind of a hack but if nothing better comes up it's something

double x = 3.14159;
double z = Math.round(x);
double r=x-z;
r*=100;
r=Math.round(r);
z=z + (r/100);

Curious Asker2010-11-08T05:40:41Z

I do not think the Math.round method will work here, so I would make my own rounding function.

// First argument is the number, second is how many places you want it to round at
public static double Round(double num, int places)
{
double power = (double)Math.pow(10, places);
num = num * power;
float temp = Math.round(num);
return (double)temp/power;
}

With this you could do....
double z = Round( x, 2);