I want to find the quotient and remainder using Java, but am having difficulty when repeating decimals are involved.
Take the following equations for example (tested with Google calculator):
division: 182.5 / (365 / 12) = 6
remainder: 182.5 % (365 / 12) = 0
Now, a simple test in Java:
System.out.println("division: " + 182.5 / (365.0 / 12));
System.out.println("remainder: " + 182.5 % (365.0 / 12));
Output:
division: 6.000
remainder: 30.415
I understand double has limitations, so I tried with BigDecimal:
BigDecimal daysInYear = new BigDecimal("365");
BigDecimal monthsInYear = new BigDecimal("12");
BigDecimal daysInMonth = daysInYear.divide(monthsInYear, 3, RoundingMode.CEILING);
BigDecimal daysInHalfYear = new BigDecimal("182.5");
BigDecimal division = daysInHalfYear.divide(daysInMonth, 3, RoundingMode.CEILING);
BigDecimal remainder = daysInHalfYear.remainder(daysInMonth);
System.out.println("division: " + division);
System.out.println("remainder: " + remainder);
Output:
division: 6.0
remainder: 30.41666666666666
What do I need to do to get the following result?
182.5 % (365 / 12) = 0