Java safe conversion of float to int

In most cases this is really not needed, if possible please keep the float as a float and work with it as such, but if needed the following works

public static Integer floatToInteger(float value){
    if (Math.round(value) < Integer.MIN_VALUE || Math.round(value) > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (value + " cannot be cast to int without changing its value.");
    }
    return (int) Math.round(value);
}

(It might be needed for instance for a switch/case as that don’t work with float – or to work with external/legacy API’s that we can not or wish not to modify)

Java Converting a int to a string

The Integer Class have a static method toString that takes a int as input and gives us back a string.

int myInt = 1;
System.out.println(Integer.toString(myInt);

This is a log more efficient and nice in the long run than just concating the int with a empty string ( myInt + “” ) as that actually creates a bit of overhead. Not much, but still.

Java safe conversion of long to int

In most cases this is really not needed, if possible please keep the long as a long and work with it as such, but if needed the following works

public static int longToInt(long value) {
    if (value < Integer.MIN_VALUE || value > Integer.MAX_VALUE) {
        throw new IllegalArgumentException
            (value + " cannot be cast to int without changing its value.");
    }
    return (int) value;
}

The reason that theLong.intValue() is not suggested here is that intValue rounds the value to fit a int – it don’t say it can’t be done.