Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round a float to the nearest quarter

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?

like image 689
Bick Avatar asked Mar 24 '11 12:03

Bick


People also ask

How do you round to the nearest quarter?

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.


1 Answers

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
like image 181
Paul Sasik Avatar answered Sep 25 '22 23:09

Paul Sasik