Java round to nearest .5 [duplicate]

@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

Leave a Comment