2013-08-26 3 views
2

Java에서 통화를 빼고 내가 읽은 값에서 Double 또는 BigDecimal을 사용할 수 있습니다. 문제는 내가 원하는대로 정확하게 작동하지 않는다는 것입니다.Double을 사용하여 Java에서 통화를 빼기

내가하고 싶은 것은 다음과 같습니다. 나는 그것이 95.30 일 다음 문자열이 값을 변환 할,

Double amount1 = 25.50; 
Double amount2 = 120.80; 

은 그때 어떤 작품 AMOUNT2에서 amount1을 빼기 싶지만는 대답은 95.3 싶지 않아.

미리 감사드립니다.

답변

1

차이를 지정하십시오.

Double amount1 = 25.50; 
Double amount2 = 120.80; 

Double diff = amount2 - amount1; 
String diffString = diff.ToString("N"); 
0

값은 95.3과 동일하다. 그러나, 당신은 예를 들면 할 수있다

string str = (amount2 - amount1); 
str += "0"; 
0

나는 그것을 해결했다라고 생각한다, 나는 다음을 사용했다.

double amount1 = 25.50; 
double amount2 = 120.80; 
double price = amount2-amount1; 
DecimalFormat formatter = new DecimalFormat("0.00"); 
String wihan = formatter.format(price); 
0

숫자 형식 -

class TstNumberFormat{ 
    public static void main(String[] args) { 
    java.text.NumberFormat f = null; 

    try { 
     Locale ll = new Locale("en", "US"); 
     f = java.text.NumberFormat.getInstance(ll); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
     f = java.text.NumberFormat.getInstance(); 
    } 

    Double amount1 = 25.50; 
    Double amount2 = 120.80; 
    f.setMinimumFractionDigits(2); 
    Double ans = amount2 - amount1; 
    String ansStr = f.format(ans.doubleValue()); 
    System.out.println("format :" + ansStr); 

} 

}

자세한 내용은 http://docs.oracle.com/javase/6/docs/api/index.html?java/text/NumberFormat.html

을위한 지역 및 번호 형식의 자바 문서를 참조
관련 문제