0

I am looking for the best way to round to even decimal values. For example I have a double = 4.267833399 and I want to round to the nearest even single decimal place, in this case 4.2 and not 4.3. And 4.3165656 would round to 4.4 not 4.3. I have searched hard and havent found a simple way to do this.

I would like the result as a double.

Thanks

DBell
  • 23
  • 2

3 Answers3

2

Assuming you want your answer in a double, this should work:

double result = Math.round(input * 5) / 5d;
BeeOnRope
  • 51,419
  • 13
  • 149
  • 309
  • Probably best to avoid using a `float`, just divide by `5.0` – Peter Lawrey Dec 07 '16 at 21:19
  • 1
    Not to be confused with `0x5d` ;) – Peter Lawrey Dec 07 '16 at 21:21
  • This is perfect thanks. Now if only I could understand the maths of it. – DBell Dec 07 '16 at 22:11
  • It's easier to understand the rounding to a single decimal point case - basically you do `Math.round(v * 10) / 10d`. That first shifts the decimal place one point to the left, then rounds it off, and then shifts it back to the left. So you can use `Math.round()` by shifting the point around to where you want it, then shifting it back. The even case with a multiplier of 5 works similarly. – BeeOnRope Dec 07 '16 at 22:35
1

You can round to one decimal place with

double d = Math.round(x * 10) / 10.0;

Note this will round 4.26 up to 4.3 as it is the closest, if you want to always round down you can do

double d = (long) (x * 10) / 10.0;

I want to round to the nearest even single decimal place

If you want to round to the nearest multiple of 0.2 you can do

double d = Math.round(x * 5) / 5.0;

This will round 4.299 to 4.2 and 4.3 to 4.4

Peter Lawrey
  • 498,481
  • 72
  • 700
  • 1,075
0

You can use something like this

double myNumber = 12345.6789;
DecimalFormat df = new DecimalFormat("#.0");
df.format(myNumber);

This would return 12345.7

Edit: Noticed you're looking for rounding to an even number. You could use the above method of rounding and then conditionally manipulate your number after if the decimal is odd.