# Thread: Rounding to one decimal place

1. Member
Join Date
Oct 2012
Posts
11
Rep Power
0

## 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.

2. ## 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)

3. Member
Join Date
Oct 2012
Posts
11
Rep Power
0

## Re: Rounding to one decimal place

Thank you but the code looks a little confusing

4. ## Re: Rounding to one decimal place

Here is an example that I put together:

Java 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!

5. Member
Join Date
Oct 2012
Posts
11
Rep Power
0

## Re: Rounding to one decimal place

So instead of 25.5069, i would have to use my 'time' variable?

6. ## 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!

7. ## 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.

8. Member
Join Date
Oct 2012
Posts
11
Rep Power
0

## Re: Rounding to one decimal place

So this a whole new method right?

Is not inside my hitsGround() method?

9. ## Re: Rounding to one decimal place

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. Member
Join Date
Oct 2012
Posts
11
Rep Power
0

## Re: Rounding to one decimal place

Thank you guys.

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•