如何将货币转换为十进制vb.net?

时间:2016-05-16 13:20:00

标签: vb.net currency

我有远程数据,我必须显示两个项目的总成本。 以下是我创建的示例,用于解决如何进行转换以添加这两项:

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

编辑:我没有展示我尝试的所有不同的演员阵容,因为我尝试过的所有演员都给出了构建错误(我认为这些演出毫无意义,因为它们在某种意义上更加不正确)。无论我如何尝试投射数字,我之所以出错是因为我的视觉工作室期望使用逗号而不是十进制值的句点,这是由于Windows中的区域设置设置不正确。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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
相关问题