Question:
How to create a code in java?
rachelle l
2010-11-07 21:22:35 UTC
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.
Three answers:
Eaf F
2010-11-07 21:34:20 UTC
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));

}





}
?
2010-11-08 05:33:13 UTC
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 Asker
2010-11-08 05:40:41 UTC
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);


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...