Problem with double @ LEARN JAVA: LOOPS Iterating Over Arrays and ArrayLists -> CalculateTotal.java

Hi there, I’m a bit confused with the output at this lesson.

public static void main(String[] args) {
    
    ArrayList<Double> expenses = new ArrayList<Double>();
    expenses.add(74.46);
    expenses.add(63.99);
    expenses.add(10.57);
    expenses.add(81.37);
    
    double total = 0;
    
    // Iterate over expenses
    for (int i = 0; i < expenses.size(); i++) {
      total += expenses.get(i);
      System.out.println(total);
    }
    
    System.out.println(total);
    
  }

This code is supposed to print sum with two digits after a dot, but instead I get this:

74.46
138.45
149.01999999999998
230.39

I wonder what is the nature of this spike. Could anyone help me?

1 Like

A brief explanation:

More detailed explanation. Even though it is from Python documentation, the floating point issue is not specific to Python or Java. All languages that deal with floating point numbers have the same issue.
https://docs.python.org/3/tutorial/floatingpoint.html#tut-fp-issues

If you want to delve deeper into the topic, then web searches for ‘floating point arithmetic problems in computers’ or similar phrases will give many results to explore.

Thank you so much for your detailed response!