Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

# Thread: take a double, then round decimal to either to .0 or .5 only

1. ## take a double, then round decimal to either to .0 or .5 only

Hi,

I have formated a double like this 9.255 will display 9.3

public double rdTwoDecimal(double d)
{
DecimalFormat twoD = new DecimalFormat("#.0");
return Double.valueOf(twoD.format(d));
}

What I now need to do is the decimal can only be .0 or .5 >>>> so 9.3 would be 9.5 when rounded.

I need to figure out how to get the 3, so I can check if it is 3,4,6,7 then display 5 maybe?

2. ## Re: take a double, then round decimal to either to .0 or .5 only

9.3 would be 9.5 when rounded.
Do you want to split on 0.3, or do you also want 0.25 to round up to 0.5? If the latter, you may get the right answer if you double the figure first, then round, then halve.

3. ## Re: take a double, then round decimal to either to .0 or .5 only

I would want .25 to be .5 too

4. ## Re: take a double, then round decimal to either to .0 or .5 only

```//lets say some double value = 9.3
double cutOff = 0.5;
if(value < (double)((int)(value))+cutOff)) //change this expression to validate your range x.0<=value<x.5 will round down to x.0
value = (double)((int)(value));
else //x.5<=value<(x+1).0 will round down to x.5
value = (double)((int)(value)) +.5```