Previous Section Table of Contents Next Section

Converting Numeric Data Types

As 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

  • Abs(): Returns the absolute value of a number, removing the positive or negative

  • CBool(): Converts a value to either True or False

  • CCur(): Converts a value to Currency

  • CDbl(): Converts a value to a Double

  • CSng(): Converts a value to a Single

  • CInt() and Int(): Converts a value to an integer

  • CLng(): Converts a value to a long integer

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.


    Previous Section Table of Contents Next Section