2014-12-13 52 views
-3

我需要顯示兩個十進制值。在做Double d=(Double) 123400/100;我得到的結果爲d=1234.0;我使用DecimalFormat,它給出的結果爲d=1234。我需要結果爲d=1234.00convert double value 123.0 to 123.00

Double d = (Double) 123400d/100; 
DecimalFormat df = new DecimalFormat("#.##"); 
System.out.print("Formatted : " + df.format(d)); 
+1

也許發佈你寫的代碼直到現在呢? – Marv 2014-12-13 16:35:41

+6

'DecimalFormat'有一個[documentation](http://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html),所以我建議你先閱讀它。 – 2014-12-13 16:36:09

+0

Double d =(Double)1234/100; System.out.print(「D =」+ d); – 2014-12-13 16:38:51

回答

2

試着這麼做:

double d= 123400/100.; 
String s = String.format("%.2f", d); 
System.out.println(s); 
0

您可以設置最小小數位數這樣

setMinimumFractionDigits(2) 

例如

public class T { 
    public static void main(String[] args) { 
     Double d = (Double) 123400.0/100; 
     DecimalFormat df = new DecimalFormat("#.##"); 
     df.setMinimumFractionDigits(2); 
     System.out.print("Formatted : " + df.format(d)); 
    } 
} 

輸出

Formatted : 1234.00 
1
Double d=(Double) 123400/100; 

此語句必須引起編譯時錯誤,指出INT無法施法翻番。

現在針對您的問題的解決方案是文本格式化。使用java.text.DecimalFormat ;.

import java.text.DecimalFormat; 

public class FormatClazz { 
    public static void main(String[] args) { 
     Double d = 123400/100 * 1.00; 
     DecimalFormat df2 = new DecimalFormat("#.00"); 
     System.out.println((df2.format(d)));  
    } 
}