fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. System.out.println(isExactFloat(0.24));
  13. System.out.println(isExactFloat(0.25));
  14. System.out.println(isExactFloat(0.5));
  15. System.out.println(isExactFloat(1.25));
  16. System.out.println(isExactFloat(2.125));
  17. System.out.println(isExactFloat(3.3125));
  18. System.out.println(isExactFloat(6.09375));
  19. System.out.println(isExactFloat(7.109375));
  20. System.out.println(isExactFloat(9.6171875));
  21. System.out.println(isExactFloat(1234567.125));
  22. }
  23.  
  24. // Determine whether number is exactly representable in double.
  25. // i.e., No rounding to an approximation during the conversion.
  26. // Results are valid for numbers in the range [2^-24, 2^52].
  27.  
  28. public static boolean isExactFloat(double val) {
  29.  
  30. int exp2 = Math.getExponent(val);
  31. int exp10 = (int) Math.floor(Math.log10(Math.abs(val)));
  32.  
  33. // check for any mismatch between the exact decimal and
  34. // the round-trip representation.
  35. int rightmost_bits = (52 - exp2) - (16 - exp10);
  36.  
  37. // create bitmask for rightmost bits
  38. long mask = (1L << rightmost_bits) - 1;
  39.  
  40. // test if all rightmost bits are 0's (i.e., no rounding)
  41. return (Double.doubleToLongBits(val) & mask) == 0;
  42. }
  43. }
  44.  
Success #stdin #stdout 0.09s 52720KB
stdin
Standard input is empty
stdout
false
true
true
true
true
true
true
true
true
true