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. public static void main (String[] args) throws java.lang.Exception
  12. {
  13. test(15.05, 9.03, 40);
  14. test(15.00, 9.00, 40);
  15. test(14.95, 8.97, 40);
  16. test(14.90, 8.94, 40);
  17. test(14.85, 8.91, 40);
  18. }
  19.  
  20. public static void test(Double oldPrice, Double price, int expected) {
  21. int discount = getPriceDifferenceInPercentage(oldPrice, price);
  22. String message = "Discount between " + oldPrice + " EUR and " + price + " EUR: " + discount + "% off";
  23. if (discount == expected) {
  24. System.out.println("OK! " + message);
  25. } else {
  26. System.out.println("FAIL! " + message + ", expected: " + expected + "% off");
  27. }
  28. }
  29.  
  30. public static int getPriceDifferenceInPercentage(Double oldPrice, Double price) {
  31. // Convert doubles to decimals with scale of 2 to make precise calculation
  32. BigDecimal oldPriceDecimal = new BigDecimal(oldPrice).setScale(2, BigDecimal.ROUND_HALF_UP);
  33. BigDecimal priceDecimal = new BigDecimal(price).setScale(2, BigDecimal.ROUND_HALF_UP);
  34.  
  35. BigDecimal percentage = oldPriceDecimal.subtract(priceDecimal).divide(oldPriceDecimal, 2, BigDecimal.ROUND_DOWN);
  36. return percentage.multiply(new BigDecimal(100)).intValue();
  37. }
  38. }
Success #stdin #stdout 0.04s 711168KB
stdin
Standard input is empty
stdout
OK! Discount between 15.05 EUR and 9.03 EUR: 40% off
OK! Discount between 15.0 EUR and 9.0 EUR: 40% off
OK! Discount between 14.95 EUR and 8.97 EUR: 40% off
OK! Discount between 14.9 EUR and 8.94 EUR: 40% off
OK! Discount between 14.85 EUR and 8.91 EUR: 40% off