I have a function that reads a text file containing two lines, it reads the second line and tries to convert the string to a Long integer. My problem is that it's not converting the string, the code for the function is as follows:
Function getLastUsed (txtFilePath)
'Read timestamp created by full backup script
Const ForReading = 1
'Error Handling
On Error Resume Next
Err.Clear
Set objFile = Fso.OpenTextFile(txtFilePath, ForReading)
'Read if file was successfully opened, else return 0
If Err.Number = 0 Then
'Value will be on the second line, so readLine twice
Dim valString
valString = objFile.Readline
valString = objFile.Readline
objFile.Close
'If not empty continue, else return 0
If Not IsEmpty(valString) Then
'Return value is IsNumeric, else return 0
If IsNumeric(valString) Then
Dim valInt
valInt = CLng(valString)'<--Won't convert, variable valInt is empty after this line
getLastUsed = valInt
Else
getLastUsed = 0
End If
Else
getLastUsed = 0
End If
Else
getLastUsed = 0
End If
End Function
I'm using Visual Studio to step through and debug, looking at the 'valInt' variable, it is empty after I call CLng or CInt. However, if I hardcode a value, like valInt = CLng("18")
it works fine. I'm not sure what I'm missing, any help is appreciated.
UPDATE
Ok so I tried running the script again, this time replacing the value in the text file, which was 20110511123500
to something shorter 2011
and it worked. So it seems like it was a precision issue. That leads to a second question, what's the largest number VBScript can handle as far as conversion is concerned? The numeric value indicated is the amount of disk space on a 开发者_开发技巧hard drive, so I need to be able to read large numbers. Thanks for the hint Pepto.
UPDATE 2
Using double did the trick, thanks G Mastros.
Maximum Numeric Value Sizes Listed Below:
Int16: -32768 to 32767
Int32: -2147483648 to 2147483647
Int64: -9223372036854775808 to 9223372036854775807
Double: -1.79769313486232E+308 to 1.79769313486232E+308
Long: -9223372036854775808 to 9223372036854775807
Short: -32768 to 32767
There is also in the System.Numerics namespace a new datatype introduced in .NET 4.0 called the BigInteger (System.Numerics.BigInteger) which can store incredibly large numbers.
More info can be found here
CDbl did the trick because the conversion required the right data type based on the numbers total size.
Going a little backwards here, but there's no need to make any conversion at all. All variables in VBScript of are type Variant. The language doesn't support true conversions. That's why comparisons can be made between values of different types. You can simply check the value with IsNumeric() and then continue on.
You should also combine your nested If statements. Since there's no Else statement in the outside branch, they can be combined:
If Not IsEmpty(valString) And IsNumeric(valString) Then ...
精彩评论