Reputation: 85
This function keeps giving me problem I cannot seem to find the right combination to get it working. I am trying to apply discount if certain amount is reached but I keep getting conversion error. What do I need to do so I define everything so it works?
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
Upvotes: 1
Views: 3787
Reputation: 54552
You really should enable Option Strict for your projects. It would help you avoid the conversion error at runtime by letting you know that you had an implicit conversion when you entered it. You could then use the Decimal.TryParse Method as BluesRockAddict and Andrew Kennan suggest.
From above link:
When you set Option Strict to On, Visual Basic checks that data types are specified for all programming elements. Data types can be specified explicitly, or specified by using local type inference. Specifying data types for all your programming elements is recommended, for the following reasons:
- It enables IntelliSense support for your variables and parameters. This enables you to see their properties and other members as you
type code.- It enables the compiler to perform type checking. Type checking helps you find statements that can fail at run time because of type conversion errors. It also identifies calls to methods on objects
that do not support those methods.- It speeds up the execution of code. One reason for this is that if you do not specify a data type for a programming element, the Visual
Basic compiler assigns it the Object type. Compiled code might have
to convert back and forth between Object and other data types, which
reduces performance.
In your case it would flag the implicit conversions in your code.
Upvotes: 2
Reputation: 13599
you need to convert you string to decimal you cant compare string to decimal like this
If System.Convert.ToDecimal(lblSubtotal.Text) > inta Then
decdiscount = 0.05
End If
Upvotes: 0
Reputation: 14157
I expect the value of lblSubtotal.Text is not a number. Perhaps try something like this:
Dim subTotal as Decimal
If Not Decimal.TryParse(lblSubTotal.Text, subTotal) Then
' Throw an exception or something
End If
If subTotal > inta Then
...
Upvotes: 0
Reputation: 15683
You should use Decimal.Parse() or Decimal.TryParse(), for example:
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
Upvotes: 1