2011-12-21 57 views
11

輸入看起來像8.7000000,我想格式化它看起來像8.70 EUR。 我考慮過使用DecimalFormat類:如何使用DecimalFormat格式化貨幣?

Double number = Double.valueOf(text); 

    DecimalFormat dec = new DecimalFormat("#.## EUR"); 
    String credits = dec.format(number); 

    TextView tt = (TextView) findViewById(R.id.creditsView); 
    tt.setText(credits); 

結果是8,7 EUR。如何告訴格式化程序在,之後有兩位數字?

+3

一般情況下,你不應該使用二進制浮點類型來存儲貨幣值反正。使用BigDecimal或只是縮放整數(例如,具有整數美分)。 – 2011-12-21 13:49:47

回答

23

也想在此強調喬恩斯基特的有關使用整型來存儲所有貨幣點 - 不希望被處理漂浮在金錢點錯誤。

使用.00,而不是## - 0表示一個數字,#表示一個數字(但隱藏它,如果它等於零)

Double number = Double.valueOf(text); 

DecimalFormat dec = new DecimalFormat("#.00 EUR"); 
String credits = dec.format(number); 

TextView tt = (TextView) findViewById(R.id.creditsView); 
tt.setText(credits); 

使用setMinimumFractionDigits?

Double number = Double.valueOf(text); 

    DecimalFormat dec = new DecimalFormat("#.## EUR"); 
    dec.setMinimumFractionDigits(2); 
    String credits = dec.format(number); 

    TextView tt = (TextView) findViewById(R.id.creditsView); 
    tt.setText(credits); 
+0

完美,謝謝! – 2011-12-21 13:44:01

+0

如果我有0.0600作爲輸入並希望6,0 ct作爲輸出,格式將如何? – 2011-12-21 13:47:18

+0

你必須在代碼中這麼做 - 我十分擔心 - Decimal格式不能應付改變單位。我想有一個條件,如果'(VAL < 1 && val > 0){//乘以100,並使用CT格式化}其他{//使用歐元格式化} – 2011-12-21 13:48:42

4

我發現這個鏈接一個很好的解決方案如下

http://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

總之

表示類似92323345465.30爲92,323,345,465.30只使用一種貨幣###,###,###,# ##。00

也就是說,只要你使用「0」,那麼「0」要麼被另一個數字來代替,或者如果沒有數字來取代它,然後它就會出現!但是你使用'#',那麼如果沒有數字來代替'#',那麼這個空間就是空的。

記住,你甚至可以添加你自己的符號,比如$,等在格式化前,甚至格式化字符串後

2

我認爲一個好的辦法是這樣的形式給出:

使用#,###.00的導致了價值0.50會顯示如下:

$ 50

然而,如果你使用#,##0.00爲同一值的結果將是:

$ 0.50