2011-02-15 90 views
2

我正在與一個數據庫進行集成,該數據庫返回貨幣(System.Decimal)和貨幣代碼。貨幣代碼是類似"USD","GBP",甚至"FRF"的字符串。C#格式貨幣給定貨幣代碼(如USD/GBP/FRF)

是否有內置的mscorlib可以幫助我格式化這些貨幣?我首先考慮設置數據庫貨幣代碼和CultureInfo之間的映射,但我不知道如何處理FRF,因爲如果我使用"fr-FR",它將格式化爲歐元而不是法郎。

我們必須支持貨幣符號的完整列表是:

FRF 
CHF 
NZD 
IN2 
SAR 
SEK 
EUR 
MXP 
DKK 
GBP 
AUD 
IN1 
AED 
CAD 
NOK 
INR 
USD 
PLN 

回答

3

可以replace the default currency,仍然利用框架的...

using System; 
using System.Globalization; 
using System.Threading; 
public class EuroLocalSample 
{ 
    public static void Main() 
    { 
    // Create a CultureInfo object for French in France. 
    CultureInfo FrCulture = new CultureInfo("fr-FR"); 
    // Set the CurrentCulture to fr-FR. 
    Thread.CurrentThread.CurrentCulture = FrCulture; 
    // Clone the NumberFormatInfo object and create 
    // a new object for the local currency of France. 
    NumberFormatInfo LocalFormat = 
    (NumberFormatInfo)NumberFormatInfo.CurrentInfo.Clone(); 
    // Replace the default currency symbol with the local 
    // currency symbol. 
    LocalFormat.CurrencySymbol = "F"; 

    int i = 100; 

    // Display i formatted as the local currency. 
    Console.WriteLine(i.ToString("c", LocalFormat)); 
    // Display i formatted as the default currency. 
    Console.WriteLine(i.ToString("c", NumberFormatInfo.CurrentInfo)); 
    } 
} 
2

這是一個非常小的列表。我只是手動設置映射。

4

我首先想到了設置數據庫貨幣代碼和CultureInfo之間的映射,但我不知道如何處理FRF,因爲如果我使用「fr-FR」,它將格式化爲歐元而不是法郎。

我會採取這種方法,但爲FRF做一個自定義IFormatProvider,它可以選擇格式。這與正確構建NumberFormatInfo一樣簡單。

+1

我認爲他們都需要進行定製。數據庫記錄中的貨幣與特定時間點的文化*相關*,而「新CultureInfo(...)`僅代表」現在「。因此,依靠*任何內置文化可能意味着貨幣符號會因Windows Update而無意中更改。這聽起來正確嗎? – tenfour 2011-02-15 17:44:00

+0

@tenfour:取決於你想要在這裏做什麼。如果你想這是可更新的,那麼他們不必定製。如果你想要這個固定的,那麼你可以使用所有的自定義verisons。然而,生成一個NumberFormatInfo非常容易,所以如果你想完全控制,在字典中創建一組定製字符串需要幾個小時的工作,最好... – 2011-02-15 17:57:32