fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.math.BigDecimal;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. /**
  12.   * Rounds a double to the specified number of decimal places using the ubiquitous "half up" rounding method
  13.   * @param numberToRound The number to be rounded
  14.   * @param numberOfDecimals The number of decimals to include in the rounded number
  15.   * @return The rounded number
  16.   */
  17. public static double round(double numberToRound, int numberOfDecimals) {
  18.  
  19. return new BigDecimal(numberToRound)
  20. .setScale(numberOfDecimals, BigDecimal.ROUND_HALF_UP)
  21. .doubleValue();
  22. }
  23.  
  24.  
  25. public static boolean checkDouble(long v) {
  26. double d = (v * 10 + 4) / 10000000.0;
  27. // v * 1,000,000 should be the same as round(d, 6) * 1000,000,000;
  28. double rescale = round(d, 6) * 1000000000.0;
  29. if (v * 1000.0 != rescale) {
  30. System.out.printf("Input %d/1000000.0 rounded to %.28f which rescaled to %.18f and not %f\n", v, round(d,6), rescale, v * 1000.0);
  31. return false;
  32. }
  33. return true;
  34. }
  35.  
  36. public static void main(String[] args) {
  37. for (long i = 0; i < 1000000; i++) {
  38. if (!checkDouble(i)) {
  39. break;
  40. }
  41.  
  42. }
  43. }
  44.  
  45. }
Success #stdin #stdout 0.12s 320256KB
stdin
Standard input is empty
stdout
Input 65/1000000.0 rounded to 0.0000650000000000000000000000 which rescaled to 64999.999999999990000000 and not 65000.000000