Easy way to keeping angles between -179 and 180 degrees

后端 未结 16 2689
长发绾君心
长发绾君心 2020-12-04 16:41

Is there an easy way to convert an angle (in degrees) to be between -179 and 180? I\'m sure I could use mod (%) and some if statements, but it gets ugly:


/         


        
16条回答
  •  情话喂你
    2020-12-04 17:15

    This works with both negative and decimal numbers and doesn't require loops, nor trigonometric functions:

    angle -= Math.floor(angle / 360 + 0.5) * 360

    The result is in the [-180, 180) interval. For (-180, 180] interval, you can use this instead:

    angle -= Math.ceil(angle / 360 - 0.5) * 360

提交回复
热议问题