Double2Float { public static float safeCasting(double d) { if (Double.isNaN(d)) { return Float.NaN; } if (Math.abs(d) == Double.MAX_VALUE) { return Float.MAX_VALUE * (d > 0 ? 1 : -1); } if (Math.abs(d) > Float.MAX_VALUE) { throw new IllegalArgumentException("Can't casting " + d + " to float"); } return (float) d; } private  Double2Float(); static float safeCasting(double d); static Float safeCasting(Double d);  }
@Test public void testCasting() { double nan = Double.NaN; assertTrue(Float.isNaN(Double2Float.safeCasting(nan))); double maxQ = Double.MAX_VALUE; assertEquals(Float.MAX_VALUE, Double2Float.safeCasting(maxQ), 1e-6); double minQ = -Double.MAX_VALUE; assertEquals(-Float.MAX_VALUE, Double2Float.safeCasting(minQ), 1e-6); Double n = null; assertNull(Double2Float.safeCasting(n)); }