Question

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.

Was it helpful?

Solution

@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

OTHER TIPS

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);

Although it is not that elegant, you could create your own Round function similarly to the following (it works for positive numbers, it needs some additions to support negatives):

public static double roundHalf(double number) {
    double diff = number - (int)number;
    if (diff < 0.25) return (int)number;
    else if (diff < 0.75) return (int)number + 0.5;
    else return (int)number + 1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top