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 feels like there must be a better way of doing this though. This is working 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 is the cleanest way to round a value to nearest 45 degrees?
I'd divide the value by 45°, round, and then multiply back by 45°. Pseudocode:
deg = round(deg / 45) * 45;
Assumption: the /
operator returns a floating-point representation and does not perform integer division. If the specific language does not treat it like this it should be handled explicitly (e.g., you could divide by 45.0
instead of 45
).
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