fork(7) 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. }
  22.  
  23. // Determine whether number is exactly representable in double.
  24. // i.e., No rounding to an approximation during the conversion.
  25. // Results are valid for numbers in the range [2^-24, 2^52].
  26.  
  27. public static boolean isExactFloat(double val) {
  28.  
  29. int exp2 = Math.getExponent(val);
  30. int exp10 = (int) Math.floor(Math.log10(Math.abs(val)));
  31.  
  32. // check for any mismatch between the exact decimal and
  33. // the round-trip representation.
  34. int rightmost_bits = (52 - exp2) - (16 - exp10);
  35.  
  36. // create bitmask for rightmost bits
  37. long mask = (1L << rightmost_bits) - 1;
  38.  
  39. // test if all rightmost bits are 0's (i.e., no rounding)
  40. return (Double.doubleToLongBits(val) & mask) == 0;
  41. }
  42. }
  43.  
Success #stdin #stdout 0.06s 47004KB
stdin
Standard input is empty
stdout
false
true
true
true
true
true
true
true
true