2013-03-29 39 views
3

今天我找到了一個簡單的問題,這個問題已經讓我成爲當天的一部分而沒有真正的成就。我試圖格式化數字以顯示爲貨幣。有很多方法可以做到這一點,我認爲我已經完成了大部分工作。使用VB.Net格式化爲貨幣數量

所以這裏的問題是:我添加了多個可以是正數和負數的數字,我不知道。當我在最後使用TextBox.Text = Format(variable, "C")進行格式化時,我得到了正數的正確格式(每個示例爲123 456,00 $,我住在加拿大),而我有(123 456,00 $)負數格式。我寧願在開始時使用「 - 」符號。

我在網上搜索了其他方法,例如: FormatCurrency("-123 456", 2, TriState.True, TriState.False)。這樣我就能擺脫括號,但是「 - 」是在編號(123 456,00 $-)之後。

下一個:SpecificCulture。所以在這裏我有NegativeValueHere.ToString("C", CultureInfo.CreateSpecificCulture("fr-CA"))。因此,我回到了開始時用括號(123 456,00 $)。請注意,我的應用程序運行時的文化設置爲("fr-CA"),因爲那是我住的地方。

我又試了一次,但不記得它是什麼。但是「$」出現在數字前面,如$-123 456,00

注意:我在VB.Net上運行,並且數字必須格式化爲只讀TextBox

+0

得到顯示的數值爲 「 - $ 123 456,00」 而不是 「$ -123 456,00」,是正確的? – Csharp

+0

那我想要數字後的$符號。但是nkvu的答案符合我的需求。感謝喚醒。 – Simon

回答

3

這似乎爲我工作:

Sub Main() 
    Dim value As Decimal = -123.45 
    Dim positiveValue As Decimal = 123.45 
    Dim customCurrencyInfo As CultureInfo = CultureInfo.CreateSpecificCulture("fr-CA") 

    customCurrencyInfo.NumberFormat.CurrencyNegativePattern = 8 

    Dim formatString As String = value.ToString("C", customCurrencyInfo) 
    Dim formatStringPositive As String = positiveValue.ToString("C", customCurrencyInfo) 

    Console.WriteLine(formatString) '-123,45 $ 
    Console.WriteLine(formatStringPositive) '123,45 $ 
    Console.ReadLine() 

End Sub 

您可以從this鏈接獲取NumberFormat.CurrencyNegativePattern不同模式的值。

很抱歉,如果我偏離軌道的

+0

Nah完全有效。我只在DataGridView的列上嘗試過NumberFormat.CurrencyNegativePattern,並且它沒有立即與TextBox一起工作,所以我沒有進一步討論。模式編號8是我需要的模式。謝謝。 – Simon

+0

嘿嘿。如果我們想要獲得其他國家的格式呢? @nkvu?我們在哪裏可以得到完整的列表,如果說我想使用馬來西亞格式/任何其他亞洲貨幣格式? – gumuruh

+0

@gumuruh運行答案中鏈接提供的[測試程序](https://msdn.microsoft.com/en-us/library/system.globalization.numberformatinfo.currencynegativepattern.aspx#Anchor_3)。 – mbomb007

4

你可以用負值貨幣值的自定義模式創建自己的文化。查看NumberFormatInfo.CurrencyNegativePattern的MSDN庫文章。例如:

Imports System.Globalization 

Module Module1 
    Sub Main() 
     Dim simon = DirectCast(CultureInfo.GetCultureInfo("fr-CA").Clone, CultureInfo) 
     simon.NumberFormat.CurrencyNegativePattern = 1 
     Dim test = -1234.567 
     Console.WriteLine(test.ToString("C", simon)) 
     Console.ReadLine() 
    End Sub 
End Module 

輸出: - 新臺幣$ 234,57

你想
+0

感謝您的提示,@Hans。我沒有意識到這一點。 – Csharp