What's the cleanest way to round a value to the nearest 45 degrees?

I have the same question as the question here .

The user asked:

I just wrote this to return the nearest 45 degree angle. Like 0, 45, 90, 135 ...

It looks like there must be a better way to do this. This works fine, but it looks messy.

    public function nearestDeg(degs:int):int {

        if (degs >= 0 && degs <= 45) {
            if (degs <= 23) {
                return 0;
            }else {
                return 45;
            }
        }

        if (degs > 45 && degs <= 90) {
            if (degs <= 68) {
                return 45;
            }else {
                return 90;
            }
        }

        if (degs > 90 && degs <= 135) {
            if (degs <= 113) {
                return 90;
            }else {
                return 135;
            }
        }

        if (degs > 135 && degs <= 180) {
            if (degs <= 158) {
                return 135;
            }else {
                return 180;
            }
        }

        if (degs > 180 && degs <= 225) {
            if (degs <= 203) {
                return 180;
            }else {
                return 225;
            }
        }

        if (degs > 225 && degs <= 270) {
            if (degs <= 248) {
                return 225;
            }else {
                return 270;
            }
        }

        if (degs > 270 && degs <= 315) {
            if (degs <= 293) {
                return 270;
            }else {
                return 315;
            }
        }

        if (degs > 315 && degs <= 360) {
            if (degs <= 338) {
                return 315;
            }else {
                return 360;
            }
        }


        return 0;

    }  

      

What's the cleanest way to round a value to the nearest 45 degrees?

+3


source to share


1 answer


I would divide the value by 45 °, round off, then multiply by 45 °. Pseudocode:

deg = round(deg / 45) * 45;

      



Assumption: The operator /

returns a floating point representation and does not perform integer division. If a particular language doesn't treat it that way, it should be handled explicitly (for example, you can split by 45.0

instead 45

).

+4


source







All Articles