O'Reilly logo

VBScript in a Nutshell, 2nd Edition by Ron Petrusha, Matt Childs, Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

CInt Function

Syntax

CInt(expression)
expression

Use: Required

Data Type: Numeric or String

The range of expression is -32,768 to 32,767; fractions are rounded.

Return Value

expression cast as an integer type.

Description

Converts expression to a type of integer; any fractional portion of expression is rounded.

Rules at a Glance

  • expression must evaluate to a numeric value; otherwise, a type mismatch error is generated.

  • If the value of expression is outside the range of the Integer data type, an overflow error is generated.

  • When the fractional part of expression is exactly 0.5, CInt always rounds to the nearest even number. For example, 0.5 rounds to 0, and 1.5 rounds to 2.

Example

<HTML>
<HEAD>
<SCRIPT LANGUAGE="VBScript">
Option Explicit

Sub cmdAdd_OnClick(  )

   Dim iSum, sNum1, sNum2
   
   sNum1 = Window.Document.frmAdd.txtText1.Value
   sNum2 = Window.Document.frmAdd.txtText2.Value
   If IsNumeric(sNum1) And IsNumeric(sNum2) Then
      iSum = CInt(sNum1) + CInt(sNum2)
      Alert "The sum is: " & iSum
   Else
      Alert "The values you enter in the text boxes must be numeric."
   End If
End Sub
</SCRIPT>
</HEAD>

<BODY>
<FORM NAME="frmAdd">
   <INPUT TYPE="text" NAME="txtText1"><BR>
   <INPUT TYPE="text" NAME="txtText2"><BR>
   <INPUT TYPE="button" NAME="cmdAdd" VALUE="Sum">
</FORM>
</BODY>
</HTML>

Programming Tips and Gotchas

  • Use IsNumeric to test whether expression evaluates to a number before performing the conversion.

  • CInt differs from the Fix and Int functions, which truncate, rather than round, the fractional part of a number. Also, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required