Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to round up float (or BigDecimal ) value by 0.5?

Tags:

java

rounding

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);
    }
}
like image 395
Meow Avatar asked Feb 04 '11 01:02

Meow


1 Answers

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.

like image 63
Mike Daniels Avatar answered Oct 13 '22 00:10

Mike Daniels