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.

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)

Re: Rounding to one decimal place

Thank you but the code looks a little confusing

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!

Re: Rounding to one decimal place

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

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!

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.

Re: Rounding to one decimal place

So this a whole new method right?

Is not inside my hitsGround() method?

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

Re: Rounding to one decimal place