Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java round to nearest .5 [duplicate]

Tags:

How is this possible in Java?

I have a float and I'd like to round it to the nearest .5.

For example:

1.1 should round to 1.0

1.3 should round to 1.5

2.5 should round to 2.5

3.223920 should round to 3.0

EDIT: Also, I don't just want the string representation, I want an actual float to work with after that.

like image 346
user1513171 Avatar asked May 03 '14 20:05

user1513171


People also ask

How do you round a double to the nearest half in Java?

Round to the nearest half For example, we use the number 5.6. double number = ((int) (input*2 + 0.5))/2.0; You do the input times 2, in this case, 11.2. Then plus 0.5, that is 11.7.

How do you round a number to the nearest multiple of 5?

If you need to round a number to the nearest multiple of 5, you can use the MROUND function and supply 5 for number of digits. The value in B6 is 17 and the result is 15 since 15 is the nearest multiple of 5 to 17.

How do you round a number to the second decimal place in Java?

1 Answer. double roundOff = (double) Math. round(a * 100) / 100; this will do it for you as well.


2 Answers

@SamiKorhonen said this in a comment:

Multiply by two, round and finally divide by two

So this is that code:

public static double roundToHalf(double d) {     return Math.round(d * 2) / 2.0; }  public static void main(String[] args) {     double d1 = roundToHalf(1.1);     double d2 = roundToHalf(1.3);     double d3 = roundToHalf(2.5);     double d4 = roundToHalf(3.223920);     double d5 = roundToHalf(3);      System.out.println(d1);     System.out.println(d2);     System.out.println(d3);     System.out.println(d4);     System.out.println(d5); } 

Output:

1.0 1.5 2.5 3.0 3.0 
like image 189
Michael Yaworski Avatar answered Sep 18 '22 15:09

Michael Yaworski


The general solution is

public static double roundToFraction(double x, long fraction) {     return (double) Math.round(x * fraction) / fraction; } 

In your case, you can do

double d = roundToFraction(x, 2); 

to round to two decimal places

double d = roundToFraction(x, 100); 
like image 40
Peter Lawrey Avatar answered Sep 20 '22 15:09

Peter Lawrey