Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 378
  • Last Modified:

Rounding off Java numbers

Hello

Could someone please run my programme below and tell me how I can round off the double values to 2 decimal places

Many thanks

/*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.*/

public class Q4
{
	public static void main (String [] args)
	{
		double start = 20;
		double years = 15;
		double interest = 10;
		double totalInt;
		
		for (int counter = 1; counter <=15; counter ++)
		{
		
		totalInt = (start / 100) * interest;
		start = start + totalInt;
						
		System.out.println("Year " + counter + " Total €" + start);
		
		}		
       }
}

Open in new window

0
Kevin_Coors
Asked:
Kevin_Coors
1 Solution
 
käµfm³d 👽Commented:
Have a look at the DecimalFormat class.
0
 
Kevin_CoorsAuthor Commented:
Thanks I have never used the Java Api before as I am a novice.

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

public class Q4
{
	public static void main (String [] args)
	{
		double start = 20;
		double years = 15;
		double interest = 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

0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now