Итак, я пишу программу, которая выполняет некоторые финансовые расчеты. Однако, поскольку я использовал double для своих типов данных, центы не округлены. Вот исходный код:Как округлить до ближайшего цента в Java
public class CentRoundingTest {
public static void main(String[] args) {
System.out.println("TextLab03, Student Version\n");
double principle = 259000;
double annualRate = 5.75;
double numYears = 30;
// Calculates the number of total months in the 30 years which is the
// number of monthly payments.
double numMonths = numYears * 12;
// Calculates the monthly interest based on the annual interest.
double monthlyInterest = 5.75/100/12;
// Calculates the monthly payment.
double monthlyPayment = (((monthlyInterest * Math.pow(
(1 + monthlyInterest), numMonths))/(Math.pow(
(1 + monthlyInterest), numMonths) - 1)))
* principle;
// calculates the total amount paid with interest for the 30 year time.
// period.
double totalPayment = monthlyPayment * numMonths;
// Calculates the total interest that will accrue on the principle in 30
// years.
double totalInterest = monthlyPayment * numMonths - principle;
System.out.println("Principle: $" + principle);
System.out.println("Annual Rate: " + annualRate + "%");
System.out.println("Number of years: " + numYears);
System.out.println("Monthly Payment: $" + monthlyPayment);
System.out.println("Total Payments: $" + totalPayment);
System.out.println("Total Interest: $" + totalInterest);
}
}
Мой инструктор также не хочет, чтобы это использовало класс DecimalFormat. Я думал получить значение центов, выполнив: variable-Math.floor (переменная), а затем округляя эту сумму до ближайшей сотой, затем добавив это вместе.
Мы не изучали класс DecimalFormat, таким образом, мы не можем его использовать. – 2014-09-29 22:50:48
Вы считаете экономить центы как int? –
@ Ивайло Карамановель, тогда мои расчеты не были бы точными. – 2014-09-29 22:52:59