# Rounding Decimal Places

• 09-28-2011, 04:36 PM
neverbend
Rounding Decimal Places
Hi

I am have been asked at college to write a programme that will calculate monthly repayments and total repayments on a loan. I have that done. I am now looking for a way to round to two deciaml places as my monthly repayment is coming up with about ten decimals places. Any suggestions on this would help, my code is below, also if you could tell me where to insert the code for this, it would be a great help!!

class Loan_Interest

{
public static void main(String args[]);

{
double intRate; //Interest rate
double initLoan; //Initial Loan Amount
double loanTerm; //Full Term of Loan
double monRepay; //Monthly repayments
double totRepay; //Total Loan repayment including interest

System.out.println("Please enter full loan amount ");
initLoan = EasyIn.getDouble();

System.out.println("Please enter interest rate, eg if the interest rate is 5%, enter 0.05 ");
intRate = EasyIn.getDouble();

System.out.println("Please enter the loan term in years ");
loanTerm = EasyIn.getDouble();

monRepay = ((initLoan * intRate) / 12) + ((initLoan / loanTerm) / 12);
totRepay = (monRepay * 12) * loanTerm;

System.out.println("Your monthly repayments are " + monRepay);

System.out.println("The total loan to be repayed over the full term of the loan is " + totRepay);
}
}
• 09-28-2011, 04:43 PM
KevinWorkman
Re: Rounding Decimal Places
Sounds like a job for DecimalFormat.
• 09-28-2011, 04:56 PM
kalambekar
Re: Rounding Decimal Places
place following piece of code after the line where you have assigned the value for monRepay

monRepay = ((initLoan * intRate) / 12) + ((initLoan / loanTerm) / 12);

double monRepayNew = rounding(monRepay,2);

totRepay = (monRepayNew * 12) * loanTerm;

System.out.println("Your monthly repayments are " + monRepayNew);

System.out.println("The total loan to be repayed over the full term of the loan is " + totRepay);
}

public static double rounding(double monRepayNew,int place){

double d = (double)Math.pow(10,place);
monRepayNew = monRepayNew * d;
double value = Math.round(monRepayNew);
return (double) value/d;
}
}
• 09-28-2011, 05:08 PM
eRaaaa
Re: Rounding Decimal Places
Use printf instead of pintln...or or or...
System.out.printf("The total loan to be repayed over the full term of the loan is %.2f \n", totRepay);
• 09-29-2011, 11:41 PM
neverbend
Re: Rounding Decimal Places
thanks folks, perfect, exactly what i needed!