I've tried with the following inputs:
principal= 1000, rate=4, timesapplied=2(half-yearly), elapsedyears=2
import javax.swing.*;
import java.math.BigDecimal;
public class CICalc {
public static void main(String[] args) {
Double principal;
Double rate;
Double timesapplied;
Double elapsedyears;
principal= Double.parseDouble(JOptionPane.showInputDialog("Enter the principal amount"));
rate=Double.parseDouble(JOptionPane.showInputDialog("Enter the Rate of Interest"));
timesapplied=Double.parseDouble(JOptionPane.showInputDialog("Enter the number of times the principal is compounded"));
elapsedyears=Double.parseDouble(JOptionPane.showInputDialog("Enter the amount of time(In years and if in months, write them in this format- month/12) the principal is being invested for"));
BigDecimal CI;
BigDecimal inf;
inf= BigDecimal.valueOf(Math.pow(rate+(1/timesapplied*100),elapsedyears*timesapplied));
CI= (BigDecimal.valueOf(principal)).multiply(inf);
BigDecimal P= CI.subtract(BigDecimal.valueOf(principal));
JOptionPane.showMessageDialog(null,"The Compound Interest for "+elapsedyears+" years is "+CI+"$ and the the interest gained is "+P+"$");
}
}
Can someone please point out the mistakes and help me out? Actually, I had made this using only Double
but the problem was that the result had way too many decimal points. So I had to use BigDecimal
.
Actually, I had made this using only Double but the problem was that the result had way too many decimal points. So I had to use BigDecimal.
Use BigDecimal setScale(int newScale, RoundingMode roundingMode) to round the result up to the required number of decimal places.
import java.math.BigDecimal;
import java.math.RoundingMode;
import javax.swing.JOptionPane;
class Main {
public static void main(String[] args) {
double principal = Double.parseDouble(JOptionPane.showInputDialog("Enter the principal amount"));
double rate = Double.parseDouble(JOptionPane.showInputDialog("Enter the Rate of Interest"));
double timesapplied = Double
.parseDouble(JOptionPane.showInputDialog("Enter the number of times the principal is compounded"));
double elapsedyears = Double.parseDouble(JOptionPane.showInputDialog("Enter the number of years"));
double base = 1.0 + rate / (timesapplied * 100.0);
double exponent = elapsedyears * timesapplied;
double inf = Math.pow(base, exponent);
double CI = principal * inf;
double P = CI - principal;
JOptionPane.showMessageDialog(null,
"The Compound Interest for " + BigDecimal.valueOf(elapsedyears).setScale(2, RoundingMode.HALF_UP)
+ " years is " + BigDecimal.valueOf(CI).setScale(2, RoundingMode.HALF_UP)
+ "$ and the the interest gained is " + BigDecimal.valueOf(P).setScale(2, RoundingMode.HALF_UP)
+ "$");
}
}