首页 > 解决方案 > 如何在 Visual Basic 中将字符串转换为十进制?

问题描述

表单有2个列表框,一个用于输入衬衫尺码和价格,另一个显示原价,点击一个按钮后,第二个列表框将原价换成折扣价(仅适用于大于100的价格) ) 它有 10% 的折扣。这部分代码给我一个错误“无法从字符串转换为十进制” For i As Integer = 0 To ListBox2.Items.Count - 1 getdiscountedprice(decprice) Decimal.TryParse(ListBox2.Items(i), decprice)

在此处输入图像描述

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim strShirt As String
    Dim strprice As String


    Dim blnmore As Boolean = True
    Do While blnmore
        strShirt = InputBox("Enter shirt: ")
        strprice = InputBox(" Enter shirt price: ")
        If strShirt = String.Empty Or strprice = String.Empty Then
            blnmore = False
        End If

        ListBox1.Items.Add(strShirt & " " & strprice)
        ListBox2.Items.Add(strprice)
    Loop
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim decprice As Decimal


    For i As Integer = 0 To ListBox2.Items.Count - 1
        getdiscountedprice(decprice)
        Decimal.TryParse(ListBox2.Items(i), decprice)

    Next
End Sub
Private Function getdiscountedprice(ByVal Fstrprice As Integer) As Decimal 'cause decimal will be returned 
    Dim lastprice As Decimal

    If Fstrprice > 100 Then
        lastprice = Fstrprice * 0.9
    End If
    Return (lastprice)

End Function

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Me.Close()
End Sub

标签: vb.netwinforms

解决方案


您需要将值从字符串转换为十进制。可以使用类型转换函数 CDec

decprice = CDec(ListBox2.Items(i).ToString)

或 Decimal 的 TryParse 方法

Decimal.TryParse(ListBox2.Items(i).ToString, decprice)

您的程序有一些问题需要解决。您的程序的一个问题是在您的 Button1_Click Sub 内的 Do While 循环中。如果字符串 strShirt 或 strPrice 之一为空,则将 blnmore 设置为 False,以便不会再次执行循环,但您仍将字符串值添加到列表框中,无论它们是否为空。只有当它们具有值时,您才应该将代码更改为列表框的字符串:

If strShirt = String.Empty OrElse strprice = String.Empty Then
    blnmore = False
Else
    ListBox1.Items.Add(strShirt & " " & strprice)
    ListBox2.Items.Add(strprice)
End If

此外,您的 getdiscountedprice 函数需要一个整数,而您将其传递给十进制。该函数返回一个 Decimal 并且您没有对该返回值执行任何操作,例如保存或打印它。您应该在调用 getdiscountedprice 之前将列表框值转换为 Decimal,而不是之后。TryParse 返回一个布尔值,指示它是否成功,您可能只想在具有有效的十进制值时调用 getdiscounted price。

If Decimal.TryParse(ListBox2.Items(i).ToString, decprice) Then
   getdiscountedprice(decprice)
End If

推荐阅读