Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit a number to a range

Tags:

java

math

I have this function to limit a rotation to the range from 0.0 to 360.0:

private float ClampRotation( float rotation ) {

    while( rotation < 0.0f ) rotation += 360.0f;
    while( rotation >= 360.0f ) rotation -= 360.0f;

    return rotation;

}

This functions works great and it probably can't be more efficient, but I'm just wondering if there are a native Java function that can do the same?

The closest I get is Math.min/max, but it doesn't work as this. A rotation of -10.0 should output 350.0 and not 0.0 as min/max would do.

like image 311
Espen Avatar asked Dec 13 '22 18:12

Espen


2 Answers

% (modulus) works on floating point values so use rotation % 360.0f (you will need to add 360.0 afterwards to negative numbers)

like image 195
The Archetypal Paul Avatar answered Jan 03 '23 09:01

The Archetypal Paul


Use the modulus operator then account for values less than 0;

private float ClampRotation( float rotation ) {

    rotation = rotation % 360f;

    if (rotation < 0f) rotation += 360f;

    return rotation;

}
like image 29
tvanfosson Avatar answered Jan 03 '23 10:01

tvanfosson