Reputation: 19071
Seems simple question but I really suck at math and few examples online I've searched seems not working for me. (the result just return the same value as input etc)
For instance.. but its in C not Java Round to Next .05 in C
So my goal is I have %.1f
format float
or double
or big decimal
and wanting to round it up to nearest .5
example:
1.3 --> 1.5
5.5 --> 5.5
2.4 --> 2.5
3.6 --> 4.0
7.9 --> 8.0
I tried following example but didn't work :( below just output 1.3 which is original value. I wanted it to be 1.5
public class tmp {
public static void main(String[] args) {
double foo = 1.3;
double mid = 20 * foo;
System.out.println("mid " + mid);
double out = Math.ceil(mid);
System.out.println("out after ceil " + out);
System.out.printf("%.1f\n", out/20.0);
}
}
Upvotes: 7
Views: 25153
Reputation: 4298
Some of the other answers round incorrectly (Math.round
should be used, not Math.floor
or Math.ceil
), and others only work for rounding to 0.5 (which is what the question asked, yes). Here's a simple method that correctly rounds to the nearest arbitrary double, with a check to assure that it's a positive number.
public static double roundToNearest(double d, double toNearest) {
if (toNearest <= 0) {
throw new IllegalArgumentException(
"toNearest must be positive, encountered " + toNearest);
}
return Math.round(d/toNearest) * toNearest;
}
Upvotes: -1
Reputation: 1306
The below formula does not work well for number like 2.16
public static float roundToHalf(float x) {
return (float) (Math.ceil(x * 2) / 2);
}
The correct answer should be 2.0, but the above method gives 2.5
The correct code should be:
public static double round(float d)
{
return 0.5 * Math.round(d * 2);
}
Upvotes: 5
Reputation: 533442
Without using a function, you can do
double rounded = (double)(long)(x * 2 + 0.5) / 2;
Note: this will round towards infinity.
Upvotes: 2
Reputation: 35372
See the Big Decimal Javadoc about why a String is used in the constructor
public static double round(double d, int decimalPlace){
BigDecimal bd = new BigDecimal(Double.toString(d));
bd = bd.setScale(decimalPlace,BigDecimal.ROUND_HALF_UP);
return bd.doubleValue();
}
Upvotes: 4
Reputation: 8642
Here's a simple method:
public static float roundToHalf(float x) {
return (float) (Math.ceil(x * 2) / 2);
}
This doubles the value, takes its ceiling, and cuts it back in half.
Upvotes: 20