How to round a float (or BigDecimal) value by 0.5?

It seems like a simple question, but I really suck in math , and the few online examples that I was looking for do not seem to work for me. (the result returns only the same value as the input, etc.)

For example .. but its in C not Java Round to Next.05 in C

So my goal: I have %.1f format float or double or big decimal and you want to round it to the 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 the following example, but did not work :( below is only output 1.3, which is the 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); } } 
+6
java rounding
source share
7 answers

Multiplying (and then dividing) by 2, not 20, should do the trick.

+8
source share

Here is an easy way:

 public static float roundToHalf(float x) { return (float) (Math.ceil(x * 2) / 2); } 

It doubles the value, takes its ceiling and cuts it in half.

+17
source share
  double nearestPoint5 = Math.ceil(d * 2) / 2; 
+4
source share

See Big Decimal Javadoc on why 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(); } 
+4
source share

The formula below is not suitable for a number such as 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); } 
+4
source share

Without using a function, you can do

 double rounded = (double)(long)(x * 2 + 0.5) / 2; 

Note: this will be rounded to infinity.

+1
source share

It is incorrect to use some other answers ( Math.round , not Math.floor or Math.ceil ), while others only work to round to 0.5 (which asked the question, yes). Here's a simple method that correctly rounds to the nearest arbitrary double, with a check to make sure it is 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; } 
-one
source share

All Articles