11

I have the following code, comments detail what should happen:

averageNum = myArray2(0) 'assign variable
response.write(TypeName(averageNum)&"<br>") 'check var type: string as expected
averageNum = CInt(averageNum) 'convert to integer

When I run this is I get

Type mismatch: 'CInt'

I need to turn the variable into an integer as I need to perform calculations with it

user692942
  • 16,398
  • 7
  • 76
  • 175
StudioTime
  • 22,603
  • 38
  • 120
  • 207
  • If `averageNum` is a string then `CInt()` should work, what does the `TypeName(averageNum)` return? You can force it to evaluate `averageNum` as a string by doing this `averageNum = myArray2(0) & ""`. – user692942 Aug 13 '14 at 14:35
  • It returns string as expected – StudioTime Aug 13 '14 at 14:36
  • What does `Response.Write "'" & averageNum & "'"` return? – user692942 Aug 13 '14 at 14:38
  • It's really weird actually, it prints the first apostrophe but not the second e.g. `'100` and if i change it to e.g. `"888 " & averageNum & " 888"` it only prints what's before the number, then the number, and not the ` 888` after it – StudioTime Aug 13 '14 at 14:49

1 Answers1

11

I would be checking that the value of myArray2(0) is an integer as you're expecting. Simple way to do this is using IsNumeric() which returns a Boolean value.

Something like this;

averageNum = myArray2(0) 'assign variable
'Check numeric value assume 0 if not numeric.
If Len(averageNum) > 0 And IsNumeric(averageNum) Then
  averageNum = CInt(averageNum) 
Else
  averageNum = 0
End If
user692942
  • 16,398
  • 7
  • 76
  • 175
  • Yeah but you're saying if it's an integer, change it to be an integer and if not set it to 0 – StudioTime Aug 13 '14 at 14:55
  • 1
    @DarrenSweeney VBScript isn't strongly typed everything is `variant` so you have to force data types using conversion functions like `CInt()` but only if it actually is a valid conversion value, hence the `IsNumeric()` check, which tell's you whether the `variant` value could be evaluated as a numeric data. – user692942 Aug 13 '14 at 14:56
  • @DarrenSweeney That is just a simple example you don't have to set `averageNum` to `0` that's all down to how you need to use it, you might prefer to raise an error for example. – user692942 Aug 13 '14 at 15:00
  • 1
    Ah ok, I get you now - and many thanks, you were indeed correct, there was a non numeric character in there which was a closing bracket, which was breaking the page... hence comments about about characters after the number failing to be seen – StudioTime Aug 13 '14 at 15:01