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 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.