fork(2) 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. /**
  11. * Round half away from zero ('commercial' rounding)
  12. * Uses correction to offset floating-point inaccuracies.
  13. * Works symmetrically for positive and negative numbers.
  14. */
  15. public static double round(double num, int digits) {
  16.  
  17. // epsilon correction
  18. double n = Double.longBitsToDouble(Double.doubleToLongBits(num) + 1);
  19. double p = Math.pow(10, digits);
  20. return Math.round(n * p) / p;
  21. }
  22.  
  23. public static void main (String[] args) throws java.lang.Exception
  24. {
  25. // test rounding of half
  26. System.out.println(round(0.5, 0)); // 1
  27. System.out.println(round(-0.5, 0)); // -1
  28.  
  29. // testing edge cases
  30. System.out.println(round(1.005, 2)); // 1.01
  31. System.out.println(round(2.175, 2)); // 2.18
  32. System.out.println(round(5.015, 2)); // 5.02
  33.  
  34. System.out.println(round(-1.005, 2)); // -1.01
  35. System.out.println(round(-2.175, 2)); // -2.18
  36. System.out.println(round(-5.015, 2)); // -5.02
  37. }
  38. }
  39.  
Success #stdin #stdout 0.06s 33080KB
stdin
Standard input is empty
stdout
1.0
-1.0
1.01
2.18
5.02
-1.01
-2.18
-5.02