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.
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.
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.
1 Answer. double roundOff = (double) Math. round(a * 100) / 100; this will do it for you as well.
@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 
                        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); 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With