Search code examples
javamathdouble

Java Turning a negative number into -1 and a positive number into 1


I've seen other posts like this but not in java. I want to convert a negative double like -6.9 and turn it into -1.0 or if its 4.2 turn it into 1.0 . I can do it with a bunch of if statements but id like to use a cleaner way.


Solution

  • This is exactly what java.util.Math's signum method does. Note that it returns a double, so you may want to cast it to an int:

    int result = (int) Math.signum(someNumber);
    

    EDIT:
    The body of the question and the title slightly contradict each other, and after re-reading the question I'm not sure if you want to get ints of 1/-1 or doubles of 1.0/-1.0. If it's the former, the above answer should do the trick. If it's the latter, you should remove the explicit cast to int, and just use signum's return value:

    double result = Math.signum(someNumber);