Search code examples
javastringcompareto

java compare to from double to int tostring method


How do i go about using compareto for a double and i want to turn it into an int?

An example would be nice. I have been searching the java api.

also is it possible to use if and else statements with a String toString method? Mine has kept on crashing for special cases.

im a total noob to java i guess i been reading constantly to learn


Solution

  • If you want to compare an integer with a double you will need to convert the integer to a double. Please be aware that this won't work the other way round as an int couldn't hold all the values a double can: Values will be round down

    double d = 12.3;
    return (int)d;
    

    will return 12! and doubles can hold values way bigger and small than int could

    double d = 1.337E42
    return (int)d;
    

    returns 2147483647! There are many orders of magnitude in between. So please always convert the int to a double to prevent this to happen.

    You can use following code for comparison:

    int compare(double d, int i) {
       return new Double(d).compareTo(new Double(i));
    }
    

    But keep in mind that Double differs from double as Double is an object and not a primitive type, so there will be more overhead when handling a Double compared to using a double or int.

    As for the second part of your question I don't really understand what's your question/intention. Please try to clarify it.