0

I am having trouble returning a precise value from a method in which I am subtracting two doubles. I am creating a "bank" software and in this method I am calculating the current interest rate which is set at 30% and is reduced by 2% whenever 5 new accounts are added.

Here is my code:

public class BankAccount {
    //static properties
    private static double interest = 0.3;
    private static ArrayList<BankAccount> accounts = new ArrayList<>();

    public static double getInterestRate() {
        int y = accounts.size();
        double x = interest;
        if (y != 0 && y % 5 == 0) {
            x-=0.02;
        }
        return x;
    }
}

After I add 5 accounts, my method should return an interest rate of 28%(.28) but it is returning a value of 27.999999999999997%(0.27999999999999997). I understand that this is due to floating points but I'm unsure how to resolve this issue. I am unable to pass any of my test cases which are all looking for exactly 28%, 26%, etc...

I'd like to use the BigDecimal class however this is a homework assignment and is graded automatically. To do so we are given a skeleton code template so we use all the correct variables and types.

  • 1
    use BigDecimal for money – Scary Wombat Mar 23 '17 at 02:20
  • If you need exact decimals, don't use `double`. Either use `BigDecimal`, or write your own class for storing these values. – Dawood ibn Kareem Mar 23 '17 at 02:24
  • 1
    Wait - are you saying your teacher _requires_ you to use `double` for this? That's extremely disappointing. I hope that in a future lesson, he/she will teach you how to do this correctly. – Dawood ibn Kareem Mar 23 '17 at 02:27
  • Yes the test cases provided as well as the test cases built into the grading software require a double to calculate the interest rate. – OlorinGrayhame Mar 23 '17 at 02:45
  • 1
    OK, but there's no such thing as a `double` with a value of exactly `0.28`. That's one of the values that the `double` datatype is simply unable to store. So you'll need to ask your teacher to clarify exactly what value the software is testing for. – Dawood ibn Kareem Mar 23 '17 at 02:48
  • 1
    Maybe the system will account for floating point error when grading your code? Even then, that would be a poor way to instill good programming practices and attention to detail in students... – SmugDoodleBug Mar 23 '17 at 03:29

0 Answers0