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);
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With