2010-09-28 127 views
2

我知道如何使用區域設置和NumberFormat類獲取貨幣的貨幣對象和其他貨幣的詳細信息。 但是我無法在API中找到任何東西來了解貨幣符號是在開始還是結束時顯示在java中特定貨幣的貨幣符號的位置

E.g.在美國10是$ 10,其中$是開頭的數字) 茲羅提10(波蘭貨幣)是10 z(z代表茲羅提符號,雖然實際符號不同)。

在數字格式或貨幣類別中是否有任何屬性可以幫助我找到貨幣符號是放置在開始還是結束?

+0

不是NumberFormat爲你處理嗎? – mlschechter 2010-09-28 01:54:32

+0

原因whny我有這個特殊的情況下處理它發送這個符號作爲前綴或後綴到一個不同的服務器,它沒有Java數字格式mechnism和格式化它的方式基本上使用區域設置的所有細節作爲不同的參數 – Fazal 2010-09-28 04:51:42

回答

1

我似乎沒有裝載很多Locales ...但法國使用尾隨符號,臺灣使用了一個前導符號。

public class MyCurrency { 
    public static void main(String[] args) { 
     System.out.println(format(Locale.FRANCE, 1234.56f)); 
     System.out.println(format(Locale.TAIWAN, 1234.56f)); 
    } 

    public static String format(Locale locale, Float value) { 
     NumberFormat cfLocal = NumberFormat.getCurrencyInstance(locale); 
     return cfLocal.format(value); 
    } 
} 

現在如果您確實想知道貨幣符號是在開頭還是在結尾,請使用以下內容作爲起點。注意bPre變量...

public String format(Locale locale, Float value) { 

    String sCurSymbol = ""; 
    boolean bPre = true; 
    int ndx = 0; 

    NumberFormat cfLocal = NumberFormat.getCurrencyInstance(locale); 
    if (cfLocal instanceof DecimalFormat) { // determine if symbol is prefix or suffix 
     DecimalFormatSymbols dfs = 
       ((DecimalFormat) cfLocal).getDecimalFormatSymbols(); 
     sCurSymbol = dfs.getCurrencySymbol(); 
     String sLP = ((DecimalFormat) cfLocal).toLocalizedPattern(); 


     // here's how we tell where the symbol goes. 
     ndx = sLP.indexOf('\u00A4'); // currency sign 

     if (ndx > 0) { 
      bPre = false; 
     } else { 
      bPre = true; 
     } 

     return cfLocal.format(value); 

    } 
    return "???"; 
} 

信用 - 我從這個頁面撕裂的代碼。 http://www.jguru.com/faq/view.jsp?EID=137963

+0

非常感謝這樣一個詳細的答案和鏈接。唯一的問題(可能是天真的)..是\\具有特殊的含義。我現在的conern案例是波蘭茲羅提貨幣,總的來說明天可能是新的。所以我想知道這個神奇的弦是否會處理所有這些。 – Fazal 2010-09-28 05:02:37

+1

我認爲這是一個格式化字符。它確實有特殊的意義 - 你想要的。這意味着,「把貨幣符號_here_」 – 2010-09-28 11:46:33