从字符串“”到“Double”类型的转换无效

时间:2012-04-26 04:02:50

标签: vb.net visual-studio-2010

这个功能一直给我带来问题我似乎找不到合适的组合让它运转起来。如果达到某些金额,我试图申请折扣,但我一直收到转换错误。我需要做什么才能定义所有内容以便它起作用?

Function coupon() As Decimal

        Dim decdiscount As Decimal
        Dim inta, intb, intc As Decimal

        inta = 20.0
        intb = 40.0
        intc = 60.0

        If lblSubtotal.Text > inta Then
            decdiscount = 0.05
        End If


        If lblSubtotal.Text > intb Then
            decdiscount = 0.1
        End If


        If lblSubtotal.Text > intc Then
            decdiscount = 0.2
        End If

        Return decdiscount
    End Function  

4 个答案:

答案 0 :(得分:2)

你真的应该为你的项目启用Option Strict。通过让您知道在输入时有隐式转换,它可以帮助您在运行时避免转换错误。然后,您可以使用Decimal.TryParse方法作为BluesRockAddict和Andrew Kennan建议。

从上面链接:

  

将Option Strict设置为On时,Visual Basic会检查该数据类型   为所有编程元素指定。数据类型可以是   显式指定,或使用本地类型推断指定。   为所有编程元素指定数据类型是   建议,原因如下:

     
      
  • 它支持IntelliSense支持您的变量和参数。这使您可以看到他们的属性和其他成员   类型代码。
  •   
  • 它使编译器能够执行类型检查。类型检查可帮助您查找因类型而在运行时失败的语句   转换错误。它还标识对对象上方法的调用   不支持这些方法的。
  •   
  • 它加快了代码的执行速度。其中一个原因是,如果您没有为编程元素指定数据类型,那么Visual   基本编译器为其指定Object类型。编译后的代码可能有   在Object和其他数据类型之间来回转换,其中   降低性能。
  •   

在您的情况下,它会标记代码中的隐式转换。

答案 1 :(得分:1)

您应该使用Decimal.Parse()Decimal.TryParse(),例如:

If Decimal.Parse(lblSubtotal.Text) > inta Then
    decdiscount = 0.05
End If

or

Dim subTotal As Decimal = Decimal.Parse(lblSubtotal.Text, Globalization.NumberStyles.AllowDecimalPoint)

If subTotal > inta Then
    decdiscount = 0.05
End If

答案 2 :(得分:0)

我希望lblSubtotal.Text的值不是数字。也许尝试这样的事情:

Dim subTotal as Decimal
If Not Decimal.TryParse(lblSubTotal.Text, subTotal) Then
' Throw an exception or something
End If

If subTotal > inta Then
...

答案 3 :(得分:0)

你需要将你的字符串转换为十进制,你不能像这样将字符串与十进制比较

  If System.Convert.ToDecimal(lblSubtotal.Text) > inta Then
            decdiscount = 0.05
        End If
相关问题