vb.net - 如何在 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
解决方案
您需要将值从字符串转换为十进制。可以使用类型转换函数 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
推荐阅读
- r - 多项式回归预测有效,但公式错误
- asp.net - Microsoft 标识和多个选项卡
- python - 计算Pyspark中每一行在列中出现的不同子字符串?
- python - 如何使用 prestapyt 编辑制造商徽标
- python - 在 PairGrid Seaborn 中仅将对数比例设置为 off_diag 图
- jenkins - Jenkins在遇到权限被拒绝状态126时没有失败构建
- sql - 如何从postgresql中的总行数中计算不同行数的百分比?
- azure - 如何使用 Jenkins 从 Azure Artifact 下载工件?
- flutter - StateError(错误状态:调用关闭后无法添加新事件)
- c# - 如何在 Blazor WASM 中对当前经过身份验证的用户帐户信息执行 CRUD 操作?