This section provides a tutorial example of writing a crash-free code logic to convert a user entered string into a Long integer value. The built-in function CLng() will crash with a string like '3.3e200'.
As a practical exercise of using variable inspection guidelines mentioned in previous sections,
let's try to solve an coding issue in a real VBScript application world.
A common task of handling user input on a Web form is to convert user entered data into a long integer.
For example, the data entered in the Order Quantity field on Web order form must be converted into a long integer
before processing the entire order.
So what code logic should you use to convert the user input data into a Long value?
This sounds like an easy task. You can you use a single statement to do this:
quantity = CLng(string_entered)
But the above code will crash, your customer enters something like "3.3e200".
So converting a used entered string into a Long value is not a simple task,
if you allow the user to type in anything. I have tried my best to write a crash-free code,
GetInteger(), to convert the input data as much as possible into a long integer
as shown in the following tutorial example, parsing_integer.html:
<html>
<body>
<!-- parsing_integer.html
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<pre>
<script language="vbscript">
document.writeln(" ")
document.writeln("Converting variants to integers:")
document.writeln(" 777 = " & GetInteger(777))
document.writeln(" ""777"" = " & GetInteger("777"))
document.writeln(" 3.14159 = " & GetInteger(3.14159))
document.writeln(" ""3.14159"" = " & GetInteger("3.14159"))
document.writeln(" ""Hello"" = " & GetInteger("Hello"))
document.writeln(" True = " & GetInteger(True))
document.writeln(" Empty = " & GetInteger(Empty))
document.writeln(" Null = " & GetInteger(Null))
document.writeln(" ""1+2"" = " & GetInteger("1+2"))
document.writeln(" 777777 = " & GetInteger(777777))
document.writeln(" 3.3e200 = " & GetInteger(3.3e200))
document.writeln(" ""3.3e20000"" = " & GetInteger("3.3e20000"))
Function GetInteger(vAnyThing)
If IsNumeric(vAnyThing) Then
' GetInteger = CInt(vAnyThing) 'Error 1: overflow on 777777
' GetInteger = CLng(vAnyThing) 'Error 2: overflow on 3.3e200
GetInteger = CDbl(vAnyThing)
If Abs(GetInteger) < 2147483647 Then
GetInteger = CLng(GetInteger)
Else
GetInteger = -2147483648
End If
Else
GetInteger = -2147483648
End If
End Function
</script>
</pre>
</body>
</html>