-1

This is a compound interest calculator, everything works fine excepts that i can't figured how to get my answer to have just 2 decimals, not a long number as right now. Please take a look at the codes and suggest if anything i should correct. Thank you very much.

class InvestmentProject{
public double CompoundInterest(double InitialDeposit, double YearlyContribution, double InterestRate, int PeriodsInYr) {

double RateInDecimal = InterestRate/100;
double Value = YearlyContribution/RateInDecimal - YearlyContribution/(RateInDecimal * Math.pow(1 + RateInDecimal, PeriodsInYr));
return (InitialDeposit + Value) * Math.pow(1 + RateInDecimal, PeriodsInYr);
}
}
Krease
  • 15,805
  • 8
  • 54
  • 86
user1825102
  • 1
  • 1
  • 1

3 Answers3

1

You should never use floats or doubles when doing financial calculations, and particularly comparisons, in Java. use BigDecimal instead. Here is an article that explains why.

Paul Sanwald
  • 10,899
  • 6
  • 44
  • 59
0

Use Math.round(result*100)/100;

There's a similar question here ( How to round a number to n decimal places in Java ) that outlines more ways of doing rounding in Java.

Community
  • 1
  • 1
Krease
  • 15,805
  • 8
  • 54
  • 86
0

You should use the decimalFormat Class

import java.text.DecimalFormat;  

public class Java0605
{
    public static void main (String args[])
    {
        DecimalFormat output = new DecimalFormat("00000");
        System.out.println(output.format(1));
        System.out.println(output.format(12));
        System.out.println(output.format(123));
        System.out.println(output.format(1234));
        System.out.println(output.format(12345));
        System.out.println(output.format(123456));
        System.out.println(output.format(1234567));
        System.out.println();
    }
}
animuson
  • 53,861
  • 28
  • 137
  • 147