How to convert from String to Decimal in Visual basic?
该表单有2个列表框,一个用于输入衬衫的尺寸和价格,另一个用于显示原始价格,单击按钮后,第二个列表框将原始价格交换为折扣价(仅适用于价格大于100的商品) )的10%折扣。 这部分代码给我一个错误"无法将字符串转换为十进制"
对于i作为整数= 0到ListBox2.Items.Count-1
getdiscountedprice(decprice)
Decimal.TryParse(ListBox2.Items(i),十价)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | 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
1 | decprice = CDec(ListBox2.Items(i).ToString) |
或用于十进制的TryParse方法
1 | Decimal.TryParse(ListBox2.Items(i).ToString, decprice) |
您的程序有一些问题需要解决。
程序的一个问题是Button1_Click子程序中的Do While循环。
如果strShirt或strPrice中的任何一个字符串为空,则将blnmore设置为False,这样就不会再次执行循环,但是无论字符串是否为空,您仍将字符串值添加到列表框中。
仅当它们具有值时,才应将代码更改为列表框中的字符串:
1 2 3 4 5 6 | If strShirt = String.Empty OrElse strprice = String.Empty Then blnmore = False Else ListBox1.Items.Add(strShirt &"" & strprice) ListBox2.Items.Add(strprice) End If |
另外,您的getdiscountedprice函数期望一个整数,并且将其传递给十进制。该函数正在返回一个十进制数,并且您没有使用该返回值执行任何操作,例如保存它或打印它。
您应该在调用getdiscountedprice之前而不是之后将列表框值转换为Decimal。
TryParse返回一个布尔值,指示是否成功,您可能只想在拥有有效的Decimal值时调用getdiscounted price。
1 2 3 | If Decimal.TryParse(ListBox2.Items(i).ToString, decprice) Then getdiscountedprice(decprice) End If |
您将类型对象放在param中并转换为十进制。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | Public Shared Function ConvertToDecimal(ByVal p_obj As Object, Optional ByVal p_isForUi As Boolean = False) As Decimal Dim dRet As Decimal If ((p_obj Is DBNull.Value) OrElse (p_obj Is Nothing)) Then dRet = Decimal.MinValue Else If (p_isForUi) Then Dim bParseOk As Boolean = Decimal.TryParse(p_obj.ToString(), dRet) Else Try dRet = CDec(p_obj) Catch exc As Exception dRet = Decimal.MinValue End Try End If End If Return dRet |