![]() |
Table of Contents |
![]() |
Converting Numeric Data TypesAs I mentioned earlier, VBScript happily converts data types for you when necessary. This process is called coercion, and it happens entirely behind the scenes as needed. There are times, however, when you want VBScript to handle data in a particular fashion. In those cases, you'll need to explicitly convert the data type. For example, in Listing 7.2, you saw how I used the Rnd() function to generate a pseudorandom number. This number is a fraction, but I wanted a whole number, and so I used the Int() function to convert it to an integer. Other numeric conversion functions include
You'll often use these functions to convert user input to a specific data type. For example, if you have an input box that accepts the number of servers to shut down, you want to make sure that's a whole number, and not some fractional number, because a fraction wouldn't make sense. You might use something like this. Dim vInput vInput = InputBox("Shut down how many servers?") If CInt(vInput) = vInput Then 'Shut them down Else MsgBox "You didn't type a whole number." End If In this case, I used CInt() to force vInput to be an integer, and then compared the result to the original value in vInput. If the two were the same, the original input was an integer and the script continues. If not, the script displays an error message and ends. TIP Never assume that some piece of data is a particular type. If the operation you are performing demands a specific type of data, you should explicitly convert your data to the proper type first. Doing so will help prevent runtime errors when unexpected conditions occur. |
![]() |
Table of Contents |
![]() |