Present value

The problem

Suppose you want to deposit a certain amount of money into a saving account, and then leave it alone to draw interest for the next 10 years. At the end of 10 years you would like to have $10,000 in the account. How much do you need to deposit today to make that happen? You can use the following formula, which is known as the present value formula, to find out:

P= F/(1/+r)^n

The terms in the formula are:

P is the present value, or the amont that you need to deposit today. F is the future value that you want in the account. (In this case, F is $10,000.) r is the annual interest rate (expressed in decimal form) n is the number of years that you plan to let the money sit in the account.

Write a program that has a function named presentValue that performs this calculation. The function should accept the future value, annual interest rate, and number of years as arguments. It should return the present value, which is the amount that you need to deposit today. Demonstrate the function in a program that lets the user experiment with different values for the formula’s terms.

Breaking it down

public static void main(String[] args) {

    // Scanner object to get input
    Scanner keyboard = new Scanner(;

    // Desired future value
    System.out.print("Future value? ");
    double futureValue = keyboard.nextDouble();

    // Annual interest rate.
    System.out.print("Annual interest rate? ");
    double annualInterestRate = keyboard.nextDouble();

    // Number of years investment to draw interest
    System.out.print("Number of years? ");
    int numberOfYears = keyboard.nextInt();

    // close scanner

    double present = calculatePresentValue(futureValue, annualInterestRate,

    // Display the result to user
    System.out.println("You need to invest $" + present);

 * Method should calculate present value
 * @param futureValue
 * @param annualInterestRate
 * @param numberOfYears
 * @return present value
public static double calculatePresentValue(double futureValue,
        double annualInterestRate, int numberOfYears) {

    return futureValue / Math.pow((1 + annualInterestRate), numberOfYears);


Future value? 1000
Annual interest rate? .10
Number of years? 10
You need to invest $385.5432894295314

Unit tests

public void test_calculatePresentValue() {

    double value = PresentValue.calculatePresentValue(1000, .10, 10);

    assertEquals(385.5432894295314, value, 0);

Level Up

  • Make the present value look pretty hint: see related examples below.
  • Interest rate is typically entered as a percentage, allow the user to choose if they would like to enter it as a percentage or a decimal.