2016-05-16 166 views
-2

我有遠程數據,我必須顯示兩項的總成本。 這裏是我創建解決如何做轉換來添加兩個項目的樣品:如何將貨幣轉換爲Decimal vb.net?

Dim test1 As String = "ZAR897.83" 
Dim test2 As String = "ZAR900.83" 
Dim t1 As Double = Val(test1) 
Dim t2 As Double = Val(test2) 
Dim TotalPrice As Decimal = 0.00 
TotalPrice += CDec(t1) 
TotalPrice += CDec(t2) 

在上面的代碼T1結果值是0.0,這是T2相同。

任何幫助添加這些值將不勝感激。

編輯:這個問題已經被問,是沒有答案在這裏:Convert currency to decimal in VB.NET

編輯:我沒有表現出各種不同的鑄件我試過,因爲所有我試過鑄件給編譯錯誤(我假設毫無意義,因爲它們在某種意義上更不正確)。之所以我得到錯誤,無論我如何嘗試投出數字,都是由於我的visual studio期望逗號而不是十進制值的時間段,這是由於Windows中的區域設置不正確。

+1

嘗試'Decimal.Parse(T1,NumberStyles.Currency)'。 –

+0

@VisualVincent「重載解析失敗,因爲沒有可訪問的'Parse'可以用這些參數調用:」它從那裏繼續添加額外的文本。 – Nightwolf

+1

如果「ZAR」應該是南非蘭特,那麼不會,你不會從Val()或Decimal.Parse()中獲得。 .NET將只接受「897.83R」。您需要先從字符串中刪除ZAR。 –

回答

3

也許你想這樣的事情

Imports System 

Public Class Program 
    Private Shared Function GetCurrencyValue(input As String) As Double 
     Dim s As String = "" 
     For i As Integer = 0 To input.Length - 1 
      If Char.IsNumber(input(i)) OrElse input(i) = "."C OrElse input(i) = "-"C Then 
       s += input(i) 
      End If 
     Next 
     Return Double.Parse(s) 
    End Function 

Public Shared Sub Main() 
    Dim test1 As String = "ZAR897.83" 
    Dim test2 As String = "ZAR900.83" 

    Dim d1 As Double = GetCurrencyValue(test1) 
    Dim d2 As Double = GetCurrencyValue(test2) 

    Dim TotalPrice As Decimal = 0.00D 

    TotalPrice += CDec(d1) 
    TotalPrice += CDec(d2) 

    Console.WriteLine(TotalPrice) 
End Sub 
End Class 
+0

第3行中的「輸入字符串格式不正確」。我也想確保它對任何貨幣都有效,因此無論如何substring都是個人問題。 – Nightwolf

+0

@Nightwolf然後檢查我的編輯 –

+1

謝謝,我用你的代碼和函數返回我需要的數字。它也給了一個錯誤,但我應該能夠解決這個問題。 – Nightwolf

0

我認爲這將有助於

To Call this function use Dim ListOfPrices As String() = {"ZAR897.83", "ZAR900.83"} Dim ReturnedPrice = ReturnVal(ListOfPrices)

Function ReturnVal(ListOfPrices As String()) 
    Dim TotalPriceInStringFormat As String = "" 
    Dim myStringVal As String = "" 
    Dim TotalPrice As Decimal = 0.0 
    Dim MyBool As Boolean = False 
    Dim count As Int16 = 0 
    For Each priceInStrFormat As String In ListOfPrices 
     TotalPriceInStringFormat = "" 
     For Each c As Char In priceInStrFormat 
      'If Char is Number or Period then append it 
      If (Char.IsNumber(c) Or c = ".") Then 
       TotalPriceInStringFormat += c 
      ElseIf (Char.IsLetter(c) And MyBool = False) Then ' Extract ZAR from "ZAR897.83" string only once 
       myStringVal += c 
       count = count + 1 
      End If 
     Next 
     If (count > 0) Then 'It already Extracted ZAR so assign MyBool to True 
      MyBool = True 
     End If 
     TotalPrice += Convert.ToDecimal(TotalPriceInStringFormat.ToString()) 
    Next 
    'If you want to return in this format ZAR900.83 Return TotalPriceWithString 
    Dim TotalPriceWithString As String = myStringVal + TotalPrice.ToString 
    'if you want return 900.83 then TotalPrice 
    TotalPrice = Convert.ToDecimal(TotalPriceInStringFormat) 

    Return TotalPrice 
End Function