2012-02-10 3 views
1

Это домашнее задание, и я пытаюсь запрограммировать калькулятор процентов. Я должен использовать класс BigDecimal, но не могу понять, как сделать вывод в валюте или процентах. Я не совсем уверен, какие вопросы задавать, но я собираюсь опубликовать оба кода с кодом класса BigDecimal, а другой, который отображает вывод так, как он мне нужен, но не использует BigDecimal. Любые предложения оценили.Java Bigdecimal class

import java.util.Scanner; 

    import java.math.*; 

    public class project3a 
    { 


     public static void main(String[] args) 
     { 
      System.out.println("Welcome to the interest calculator"); 
      System.out.println(); 


      // create a scanner object and start while loop    
      Scanner sc = new Scanner(System.in); 
      String choice ="y"; 
      while (choice.equalsIgnoreCase("y")) 
      { 

      //Get input from user 
      System.out.print("Enter Loan amount: "); 
      double Loanamount = sc.nextDouble(); 

      System.out.print("Enter Interest Rate: "); 
      double interestrate = sc.nextDouble(); 

      //calculate results  
      double Interest = Loanamount * interestrate; 

      //format 
      BigDecimal decimalLoanamount = new BigDecimal(Double.toString (Loanamount)); 
      decimalLoanamount = decimalLoanamount.setScale(2, RoundingMode.HALF_UP); 
      BigDecimal decimalinterestrate = new BigDecimal(Double.toString(interestrate)); 
      BigDecimal decimalInterest = new BigDecimal (Double.toString(Interest)); 
      decimalInterest = decimalInterest.setScale(2,RoundingMode.HALF_UP); 

      //Display results 
      System.out.println("Loan amount: " + decimalLoanamount); 
      System.out.println("Interest rate: " + decimalinterestrate); 
      System.out.println("Interest:" + decimalInterest); 
      System.out.println(); 

      //see if user wants to continue    
      System.out.print("Continue? (y/n): "); 
      choice = sc.next(); 
      System.out.println(); 


     } 

    } 

    } 

import java.util.Scanner; 
    import java.text.NumberFormat; 
    import java.math.*; 

    public class project3a 
    { 


    public static void main(String[] args) 
    { 
     System.out.println("Welcome to the interest calculator"); 
     System.out.println(); 


     // create a scanner object and start while loop    
     Scanner sc = new Scanner(System.in); 
     String choice ="y"; 
     while (choice.equalsIgnoreCase("y")) 
     { 

      //Get input from user 
      System.out.print("Enter Loan amount: "); 
      double Loanamount = sc.nextDouble(); 

      System.out.print("Enter Interest Rate: "); 
      double interestrate = sc.nextDouble(); 

      //calculate results 
      double Interest = Loanamount * interestrate; 

      //format and display results 
      NumberFormat currency = NumberFormat.getCurrencyInstance(); 
      NumberFormat percent = NumberFormat.getPercentInstance(); 
      String message = 
       "Loan amount: " + currency.format (Loanamount) + "\n" 
       + "Interest rate: " + percent.format (interestrate)+ "\n" 
       + "Interest:  " + currency.format (Interest) + "\n"; 

      System.out.println(message); 

      //see if user wants to continue    
      System.out.print("Continue? (y/n): "); 
      choice = sc.next(); 
      System.out.println(); 


     } 

    } 

    } 
+3

Чем меньше кода, тем лучше вопрос и тем быстрее и лучше ответ. –

+2

Я просто пытался показать, что я прилагаю усилия, а не просто ловить рыбу, потому что это домашнее задание. –

+1

Можете ли вы уточнить, какой результат вы ожидали и что получаете? Есть ли 'currency.format()' и 'percent.format()' ваша проблема? –

ответ

0

BigDecimal есть метод doubleValue(), который можно использовать в NumberFormat.

BigDecimal bd = new BigDecimal("15.25"); 
NumberFormat currency = NumberFormat.getCurrencyInstance(); 
NumberFormat percent = NumberFormat.getPercentInstance(); 

System.out.println(currency.format(bd.doubleValue())); //In Brazil outputs R$ 15,25 
System.out.println(percent.format(bd.doubleValue())); // 1.525% 
+1

Если вы хотите использовать представление без плавающей запятой, чтобы избежать плавающих ошибок, вы не должны повторно вводить ошибки представления с плавающей запятой в конце, преобразовывая их в double. http://www.javaworld.com/javaworld/jw-06-2001/jw-0601-cents.html говорит: «Поэтому вы не можете полагаться на NumericFormat для получения точных результатов с очень большими номерами (около 13 или более цифр). " –

+0

@MikeSamuel Спасибо за ссылку, интересный момент! –

+1

['BigDecimal.format (Object, ...)'] (http://docs.oracle.com/javase/1.5.0/docs/api/java/text/DecimalFormat.html#format%28java.lang. Объект,% 20java.lang.StringBuffer,% 20java.text.FieldPosition% 29) не имеет одинаковую оговорку о преобразовании 'BigDecimal' в' double', как это делает 'NumberFormat'. –