Nightwolf Nightwolf - 1 year ago 61 Question

How to convert currency to Decimal

I have remote data that I have to display the total cost of two items.
Here is a sample I created to troubleshoot how to do the conversion to add the two items:

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)

In the code above t1 resulted value is 0.0 and it is the same for t2.

Any help to add these values will be appreciated.

Edit: This question has been asked and was unanswered here: Convert currency to decimal vb .net

Edit: I did not show all the different castings I tried because all the castings I tried gave build errors (which I assumed to be pointless to show because they were in a sense more incorrect). The reason why I got errors no matter how I tried to cast the numbers was due to my visual studio expect a comma instead of a period for decimal values and this was due to region settings in windows set up incorrectly.

Answer Source

Maybe you want something like that

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
        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)

End Sub
End Class