fork(3) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.math.*;
  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. int bdErrors = 0, doubleErrors = 0;
  13. for(BigDecimal bd = BigDecimal.ZERO; bd.compareTo(BigDecimal.ONE) <=0 ; bd = bd.add(new BigDecimal("0.0001"))) {
  14. // test BigDecimal rounds as expected.
  15. BigDecimal bd2 = bd.setScale(2, RoundingMode.HALF_UP);
  16. BigDecimal error = bd2.remainder(new BigDecimal("0.01"));
  17. if (error.compareTo(BigDecimal.ZERO) != 0)
  18. bdErrors++;
  19. // now try this with double.
  20. double d = bd.doubleValue();
  21. double d2 = Math.round(d * 100) / 100.0;
  22.  
  23. // has any information been lots, use BigDecimal to do calculations to be sure of no accidental errors.
  24. BigDecimal bd3 = BigDecimal.valueOf(d2);
  25. BigDecimal error3 = bd3.remainder(new BigDecimal("0.01"));
  26. if (error3.compareTo(BigDecimal.ZERO) != 0)
  27. doubleErrors++;
  28.  
  29. }
  30. System.out.printf("BigDecimal errors %,d & double errors %,d%n", bdErrors, doubleErrors);
  31. }
  32. }
Success #stdin #stdout 0.28s 380800KB
stdin
Standard input is empty
stdout
BigDecimal errors 0 & double errors 0