2016-10-06 1 views
0

저는 Java에 익숙하지 않고 신용 카드 청구를 추가하고 청구에이자를 추가하는 신용 ​​카드 Java 할당을 코딩하고 있습니다. If 문을 사용하여 관심을 코딩했지만 반올림되지 않은 소수점으로 출력합니다. 이 같은Java에서 if 문을 사용할 때 어떻게 십진법을 반올림합니까?

public class Credit_Card 
{ 
    public static void main (String []args) 
    { 
     Scanner c = new Scanner (System.in); 
     double num1, num2, interest, newBalance, min = 0; 

     int num3 = 50; 

     System.out.println ("What is the previous balance?"); 
     num1 = c.nextInt(); 

     System.out.println ("What is the total amount of additional  charges?"); 
     num2 = c.nextInt(); 

     interest = num2; 

     if (num2 == 0) 
     interest = (interest + 0); //There is no interest if num2 is 0 

     if (num2 > 0) 
     interest = (interest*(2.0f/100.0f)); //total amount of money owed is multiplied by 2 percent 

     newBalance = num1 + num2 + interest; 

     System.out.println ("CS CARD International Statement"); 
     System.out.println ("==============================="); 
     System.out.println (""); 
     System.out.println ("Previous Balance:  $" + num1); 
     System.out.println ("Additional Charges: $" + num2); 
     System.out.println ("Interest:    $" + interest); 
     System.out.println (""); 
     System.out.println ("New Balance:   $" + newBalance); 
     System.out.println (""); 

     if (newBalance < 50) 
     min = newBalance; 

     if(newBalance >= 50 && newBalance <= 300) 
     min = num3; 

     if(newBalance > 301) 
     min = (newBalance*(20.0f/100.0f)); 

     System.out.println ("Minimum Payment:  $" + min); 
    } 
} 

출력의 모양을

What is the previous balance? 
1000 
What is the total amount of additional charges? 
25 
CS CARD International Statement 
=============================== 

Previous Balance:  $1000.0 
Additional Charges: $25.0 
Interest:    $0.4999999888241291 

New Balance:   $1025.4999999888241 

Minimum Payment:  $205.100003053993 

내가 생각하는 관심이 영원한 소수점 다른, 그것은 나사까지 모든 것을이기 때문이다. 관심사가 "0.49999999999"가 아닌 "0.50"처럼 좋아합니다. 어떤 도움을 주셔서 미리 감사드립니다. var이 뉴 발란스입니다

+1

보세요 [여기] (http://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-in-java) – blackpen

+0

'if' 문이 없습니다. 반올림과 관련이 없습니다. 부동 소수점으로 돈을 계산해서는 안됩니다. – EJP

답변

3

String.format ("%.2f", var);는 등

이 소수점 이하 2 자리로 반올림합니다.

포맷터로 수행 할 수있는 작업의 목록은 https://www.dotnetperls.com/format-java을 확인하십시오.

+0

"String.format"을 삽입 할 곳이 약간 혼란 스럽습니다. 그것을 당신과 바꾸시겠습니까 : interest = (interest * (2.0f/100.0f)); –

+1

인쇄물 내부. –

+0

"% .2f"에 대해 정확히 입력 했습니까? 아니면 "%"를 백분율로 대체합니까? 이자가 반올림되지 않았기 때문에 "newBalance"대신 "var"에 넣을까요? 오해와 죄송합니다. –

관련 문제