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)