Java Possible loss of Precision ????


Is there anyway I can fix the 'possible loss of precision' error in my Java program below without changing the int value 'start' to a double?

/*4. Write a program to calculate and display the amount of money in a bank
account that was opened with a deposit of €20 fifteen years ago and has
earned interest at 10% (compound interest) per annum. Your program
should display the amount of money in the account at the end of each year
for all of the 15 years. Your program should also display the total interest
earned at the end of 15 years.*/

import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Q4_Int_Double
	public static void main (String [] args)
		int start = 20;
		double interest = 0.10;
		double totalInt;
		NumberFormat formatter = new DecimalFormat("0.00");
		for (int counter = 1; counter <=15; counter ++)
		totalInt = (start / 100) * interest;
		start = start + totalInt;
		System.out.println("Year " + counter + " Total €" + formatter.format(start));


Open in new window

Who is Participating?
käµfm³d 👽Connect With a Mentor Commented:
Not every integer divides another integer into equal parts, correct? This means that when you divide two arbitrary numbers, depending on the numbers there is a chance that a fractional part will remain (e.g. 3 / 2). When you divide two integers in Java, any fractional part is truncated off. This is what the error message is telling you. You need to account for this by not dividing two integers. Rather you need to divide with at least one floating point (fractional) value. Can you think of a way to turn either start or 100 into a floating point value?


Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.