Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP Classic - Type mismatch: 'CInt' - Easy question

Tags:

asp-classic

Having an issue with type conversion in ASP classic.

heres my code:

        Set trainingCost = Server.CreateObject("ADODB.Recordset")
    strSQL3 = "SELECT cost1 FROM tblMain WHERE (Booked = 'Booked') AND (Paid IS NULL) AND (PaidDate BETWEEN '01/04/" & startyear & "' AND '31/03/" & endyear & "')"
    trainingCost.Open strSQL3, Connection
    trainingCost.movefirst
    totalTrainCost = 0
    do while not trainingCost.eof
        trainCost = trainingCost("cost1")
        If NOT isNull(trainCost) then
            trainCostStr = CStr(trainCost)
            trainCostStr = Replace(trainCostStr, "£", "")
            trainCostStr = Replace(trainCostStr, ",", "")
            totalTrainCost = totalTrainCost + CInt(trainCostStr)
        end if
        trainingCost.movenext
    loop 

    trainingCost.close

when I run this I get the following error:

Microsoft VBScript runtime (0x800A000D) Type mismatch: 'CInt' /systems/RFT/v1.2/Extract.asp, line 43

which is "totalTrainCost = totalTrainCost + CInt(trainCostStr)"

Im guessing that the problem is to do with the String value being uncastable to Int in which case is there any way to catch this error? I havent worked with asp classic much so any help would be usefull

cheers

-EDIT-

the type of column cost1 is String as it may contain a number or a sequence of chars eg £10.00 or TBC

like image 940
Jambobond Avatar asked Dec 08 '22 06:12

Jambobond


1 Answers

You have a couple of choices. You can be proactive by checking ahead of time whether the value is numeric using the IsNumeric function:

 If IsNumeric(trainCostStr) Then
    totalTrainCost = totalTrainCost + CInt(trainCostStr)
 Else
    ' Do something appropriate
 End If

...or you can be reactive by using error catching; in Classic ASP probably easiest to define a function and use On Error Resume Next:

Function ConvertToInt(val)
    On Error Resume Next
    ConvertToInt = CInt(val)
    If Err.Number <> 0 Then
        ConvertToInt = Empty
        Err.Clear
    End If
End Function

Or return 0 or Null or whatever suits you, then use it in your trainCost code.

Note that CInt expects an integer and will stop at the first non-digit, so "123.45" comes back as 123. Look at the other conversions, CDouble, CCur, etc.

like image 186
T.J. Crowder Avatar answered Jan 04 '23 01:01

T.J. Crowder