2014-09-29 3 views
0

Итак, я пишу программу, которая выполняет некоторые финансовые расчеты. Однако, поскольку я использовал 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 (переменная), а затем округляя эту сумму до ближайшей сотой, затем добавив это вместе.

+0

Мы не изучали класс DecimalFormat, таким образом, мы не можем его использовать. – 2014-09-29 22:50:48

+2

Вы считаете экономить центы как int? –

+0

@ Ивайло Карамановель, тогда мои расчеты не были бы точными. – 2014-09-29 22:52:59

ответ

1

без использования JDK-предоставляемых библиотеки классов, которые существуют для этой цели (и, как правило, используются), псевдокод для округления арифметический является:

  • умножить на 100, что дает вам центы
  • надстройку (или вычитать, если число отрицательное) 0.5, поэтому следующий шаг округляется до ближайшего цента
  • литая к int, который обрезает дробную часть
  • разделить на 100d, давая вам долларов)

Теперь перепишите код.

+0

Это не работает для ежемесячного платежа, дающего мне 1511.0 вместо 1511.45 – 2014-09-29 23:00:54

+1

«100» на последнем шаге должен быть «double», поэтому добавьте к нему «d», 100d' - см. Отредактированный ответ. Если вы этого не сделаете, вы получите целочисленную арифметику. Если один операнд является с плавающей запятой, результатом является плавающая запятая. – Bohemian

+0

хорошо спасибо, это сработало Я использовал 100.00 – 2014-09-29 23:10:09

0

Ну, если вы не можете использовать DecimalFormat класс, вы могли бы использовать printf():

TextLab03, Student Version 

Principle  : $259,000.00 
Annual Rate  : 5.75% 
Number of years : 30.00 
Monthly Payment : $1,511.45 
Total Payments : $544,123.33 
Total Interest : $285,123.33 
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; 

     printAmount("Principle", principle); 
     printPercent("Annual Rate", annualRate); 
     printCount("Number of years", numYears); 
     printAmount("Monthly Payment", monthlyPayment); 
     printAmount("Total Payments", totalPayment); 
     printAmount("Total Interest", totalInterest); 
    } 

    public static void printPercent(String label, double percentage) { 
     //System.out.printf("%-16s: %,.2f%%%n", label, percentage); 
     printNumber(label, percentage, "", "%", 16); 
    } 

    public static void printCount(String label, double count) { 
     //System.out.printf("%-16s: %,.2f%n", label, count); 
     printNumber(label, count, "", "", 16); 
    } 

    public static void printAmount(String label, double amount) { 
     //System.out.printf("%-16s: $%,.2f%n", label, amount); 
     printNumber(label, amount, "$", "", 16); 
    } 

    public static void printNumber(String label, double value, String prefix, String suffix, int labelWidth) { 
     String format = String.format("%%-%ds: %%s%%,.2f%%s%%n", labelWidth); 
     System.out.printf(format, label, prefix, value, suffix); 
    } 
} 
Смежные вопросы