# Rounding to one decimal place

• 10-16-2012, 01:24 AM
threlot
Rounding to one decimal place
Hello,

Im using Bluej :

public double hitsGround()
{
double currentHeight = 0;
double time = 0;

do
{
currentHeight = initialHeight + velocity * time - 16 * time * time;
time = time + 0.1;

} while (currentHeight >= 0);

return time;

}
}

I want the code to return the 'time' as one decimal place.
I don't know what to do.

Thanks for the help.
• 10-16-2012, 01:37 AM
joshdgreen
Re: Rounding to one decimal place
You will need to reference the decimal formatting class for this. You can find the information you need here: DecimalFormat (Java 2 Platform SE v1.4.2)
• 10-16-2012, 02:05 AM
threlot
Re: Rounding to one decimal place
Thank you but the code looks a little confusing
• 10-16-2012, 02:34 AM
joshdgreen
Re: Rounding to one decimal place
Here is an example that I put together:

Code:

```import java.text.DecimalFormat; public class test {         public static void main(String[] args)         {                 double number = 25.5069;                 DecimalFormat df = new DecimalFormat(".#");                                 System.out.println("Number before: " + number);                 System.out.print("Number after: " + df.format(number));         } }```
First you will to import the Decimal Format class (shown at the top). Then inside your code you will need to create a Decimal Format variable. This will be used to changed the output of your double to one decimal place e.g. ".#" in the code. Hope this helps a little more!
• 10-16-2012, 02:44 AM
threlot
Re: Rounding to one decimal place
So instead of 25.5069, i would have to use my 'time' variable?
• 10-16-2012, 02:45 AM
joshdgreen
Re: Rounding to one decimal place
If you are returning time to one decimal place, yes, you would do something like... return df.format(time). You're on the right track!
• 10-16-2012, 03:17 AM
Junky
Re: Rounding to one decimal place
Important to remember is that the DecimalFormat class does not change the value of the variable. It simply returns a String representation of the value. That means if you have a variable with the value 1.234 DecimalFormat will give 1.2 but 1.234 will still be stored in the variable.
• 10-16-2012, 03:30 AM
threlot
Re: Rounding to one decimal place
So this a whole new method right?

Is not inside my hitsGround() method?
• 10-16-2012, 03:38 AM
joshdgreen
Re: Rounding to one decimal place
Quote:

Originally Posted by threlot
So this a whole new method right?

Is not inside my hitsGround() method?

You can put it wherever you want it. Inside your hitsGround() method would work...
• 10-16-2012, 05:52 AM
threlot
Re: Rounding to one decimal place
Thank you guys.