Sometimes I need to round a float to the nearest quarter and sometimes to the nearest half.
For the half I use
Math.round(myFloat*2)/2f
I can use
Math.round(myFloat*4)/4f
.
but is there any other suggestions?
Firstly, Check the two digits sequence next to the decimal place value. If xy mod(25) > 12 then round up and the nearest quarter is xy + (25 – xy mod(25)). On rounding up if you get the nearest quarter ending in . 00 then increase the one's place value by 1.
All you need is:
Math.round(myFloat*4)/4f
Since a half is also two quarters this single equation will take care of your half-rounding as well. You don't need to do two different equations for half or quarter rounding.
Code Sample:
public class Main {
public static void main(String[] args) {
float coeff = 4f;
System.out.println(Math.round(1.10*coeff)/coeff);
System.out.println(Math.round(1.20*coeff)/coeff);
System.out.println(Math.round(1.33*coeff)/coeff);
System.out.println(Math.round(1.44*coeff)/coeff);
System.out.println(Math.round(1.55*coeff)/coeff);
System.out.println(Math.round(1.66*coeff)/coeff);
System.out.println(Math.round(1.75*coeff)/coeff);
System.out.println(Math.round(1.77*coeff)/coeff);
System.out.println(Math.round(1.88*coeff)/coeff);
System.out.println(Math.round(1.99*coeff)/coeff);
}
}
Output:
1.0
1.25
1.25
1.5
1.5
1.75
1.75
1.75
2.0
2.0
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