Results 1 to 10 of 10

Thread: [RESOLVED] Cast from String to type double is not valid

  1. #1

    Thread Starter
    Junior Member
    Join Date
    May 2010
    Posts
    26

    Resolved [RESOLVED] Cast from String to type double is not valid

    I am currently going through a book on beginning VB,NET and am trying to complete one of the exercises in the book. I have created a function that validates user entries to check that they are numeric and within certain a range.

    If text value is entered into the textbox I get an exception error saying that

    "Cast from String to type double is not valid"

    The main code is as follows:

    Code:
    Private Sub btnCalculate_Click(ByVal sender As System.Object, _
                ByVal e As System.EventArgs) Handles btnCalculate.Click
    
            
    
            Dim dOrderTotal As Decimal
            Dim dDiscountPct As Decimal
            Dim dDiscountAmount As Decimal
            Dim dInvoiceTotal As Decimal
    
    
    
            If ValidEntry(txtOrderTotal.Text) = 0 Then
                dDiscountAmount = DiscAmount(dOrderTotal)
                dInvoiceTotal = dOrderTotal - dDiscountAmount
                lblDiscountAmount.Text = FormatNumber(dDiscountAmount)
                lblInvoiceTotal.Text = FormatNumber(dInvoiceTotal)
            ElseIf ValidEntry(txtOrderTotal.Text) = 1 Then
                ' Not IsNumeric
                MessageBox.Show("You must enter a numeric value.", "Entry error")
            ElseIf ValidEntry(txtOrderTotal.Text) = 2 Then
                ' Out of Range Value
                MessageBox.Show("Order total must be between 10 and 10000", "Entry error")
            End If
    
            txtOrderTotal.Focus()
    
        End Sub
    
    
    
    Module CalcModule
    
        Const dMinOrderTotal As Decimal = 10
        Const dMaxOrderTotal As Decimal = 10000
        Public Function DiscAmount(ByVal Ordertot As Decimal) As Decimal
    
            Dim dDiscount As Decimal, dDisAmount As Decimal
    
            If Ordertot >= 500 Then
                dDiscount = 0.2
            ElseIf Ordertot >= 250 Then
                dDiscount = 0.15
            ElseIf Ordertot >= 100 Then
                dDiscount = 0.1
            Else ' < 100
                dDiscount = 0
            End If
    
            dDisAmount = dDiscount * Ordertot
    
            Return (dDisAmount)
        End Function
        Public Function ValidEntry(ByVal OrderTotal As String) As Integer
    
            Dim dValidType As Integer
            ' 0 = valid entry
            ' 1 = nonnumeric
            ' 2 = invalidrange
    
           If IsNumeric(OrderTotal) And OrderTotal >= dMinOrderTotal And OrderTotal <= dMaxOrderTotalIf IsNumeric(OrderTotal) And OrderTotal >= dMinOrderTotal And OrderTotal <= dMaxOrderTotal Then
                dValidType = 0
            ElseIf IsNumeric(OrderTotal) And (OrderTotal < dMinOrderTotal Or OrderTotal > dMaxOrderTotal) Then
                dValidType = 2
            Else
                dValidType = 1
            End If
            Return dValidType
    
        End Function
    End Module
    The highlighted code is where the exception is thrown.
    Any help to solve this would be appreciated.

  2. #2
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Cast from String to type double is not valid

    Use
    Double.TryParse method.

    Code:
    ' this will cast string to double:
    Dim str As String = "3.14"
    Dim d As Double = 0
    
    If Not Double.TryParse(str, d) Then
       ' The string is in invalid format
    End If

  3. #3

    Thread Starter
    Junior Member
    Join Date
    May 2010
    Posts
    26

    Re: Cast from String to type double is not valid

    HI i am relatively new to VB.NET. I have tried to add TryParse to my code but get an error saying that:

    Argument not specified for parameter 'result' pf [ublic Shared Function TryParse

    my amended code is:
    Code:
    Dim dValidType As Integer
    Dim d As Double = 0
    
    If Double.TryParse(OrderTotal, d) And OrderTotal >= dMinOrderTotal And OrderTotal <= dMaxOrderTotal Then
                dValidType = 0
    ElseIf Double.TryParse(OrderTotal, d) And (OrderTotal < dMinOrderTotal Or OrderTotal > dMaxOrderTotal) Then
             dValidType = 2
    Else
             dValidType = 1
    
    End If
    Return dValidType

  4. #4
    New Member
    Join Date
    Nov 2010
    Posts
    13

    Re: Cast from String to type double is not valid

    Let the parameter in your function be of type Object. In your function do the IsNumeric check first. In the If statement each condition is evaluated even if the first fails.

  5. #5

    Thread Starter
    Junior Member
    Join Date
    May 2010
    Posts
    26

    Re: Cast from String to type double is not valid

    I am relatively new vb.net Why should the parameter in the function be of type object?

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Cast from String to type double is not valid

    Ok, there are a couple problems here. First off, use AndAlso and OrElse rather than And/Or. The reason for doing this is that And will evaluate all pieces of the If statement, while AndOr will stop evaluating once the overall answer is known. Therefore, if the first part (the TryParse) is False, then there is no point in even evaluating the rest. Using And, the rest will be evaluated anyways. Using AndAlso, the rest will not be evaluated.

    The next point is that Option Strict should be ON. That makes the resulting code faster and avoids some simple bugs such as the one in that If statement. Using Option Strict, you will become a better coder, make less errors, and end up with faster code. It's just a good idea all around, and should be the set as a default for ALL of your projects (it can be set in the Project|Properties, or by code page, but the former is much better than the latter).

    Lastly, while you do convert the string to a double with TryParse, you then promptly ignore the double (which is in d), and try to compare the string (orderTotal) to a double. The only way to do that would be for the compiler to implicitly convert orderTotal to a double and perform the comparison. You just did an explicit conversion with the TryParse statement, so why perform the slower implicit conversion in the very next part of the statement? Option Strict would prevent that. Using AndAlso would mean that the second comparison wouldn't even have happened if the string couldn't be converted to a double, and it's just a bad idea anyways. So those are the three points.
    My usual boring signature: Nothing

  7. #7

    Thread Starter
    Junior Member
    Join Date
    May 2010
    Posts
    26

    Re: Cast from String to type double is not valid

    Hi

    Thanks for the imformation. I took actually changed the code as following. The argument of my function was changed to control and put the isnumeric check first on its own.

    Code:
    Public Function ValidEntry(ByVal OrderTotal as Control) As integer
    
    Dim dValidType As integer
    Dim dOrdTot As Decimal
    
    
    If Isnumeric(OrderTotal.Text) Then
    
      If OrderTotal.Text >= dMinOrderTotal And OrderTotal.Text <= dMaxOrderTotal Then
          dValidType = 0
      Else
         dValidType = 2
      End If
    Else
        dValidType = 1
    End If
    
    Return dValidType
    
    End Function
    My reason for doing so was that i wanted to keep in line with the level I was at with the book I am reading. I will definitely takeon board what you have suggested for future reference. In the meantime I got the application to work.

    Regards
    Sauce1979

  8. #8
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Cast from String to type double is not valid

    That certainly matters. I'm a bit surprised that a book on .NET would advocate IsNumeric, though.
    My usual boring signature: Nothing

  9. #9
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Cast from String to type double is not valid

    It shocks me even more that passing in a control like that would be "acceptable" ... but eh, you know, it seems like the academic world and increasingly the published world doesn't seem to want (or find it necessary) to teach real-world context or generally accepted best practices. Everything seems to be contrived these days.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  10. #10
    PowerPoster cicatrix's Avatar
    Join Date
    Dec 2009
    Location
    Moscow, Russia
    Posts
    3,654

    Re: Cast from String to type double is not valid

    Quote Originally Posted by Shaggy Hiker View Post
    That certainly matters. I'm a bit surprised that a book on .NET would advocate IsNumeric, though.
    Any idiot can write a book, I noticed.
    The code above makes me think that this style was suggested by a php coder. )

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width