Reputation: 23
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
Upvotes: 0
Views: 2412
Reputation: 64895
Assuming you want your answer in a double
, this should work:
double result = Math.round(input * 5) / 5d;
Upvotes: 2
Reputation: 533442
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
Upvotes: 1
Reputation: 1
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.
Upvotes: 0