Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
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.
3 Answers
- Eaf FLv 41 decade agoFavorite 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));
}
}
Source(s): The method I described is the correct way to do it. It is senseless to write your own method when there is a perfectly good built in function - 1 decade ago
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);
- 1 decade ago
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);