Name

CSng Function

Syntax

CSng(expression)
expression

Use: Required

Data Type: Numeric or String

The range of expression is -3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to 3.402823E38 for positive values.

Return Value

expression cast as a type of Single.

Description

Returns a single-precision number.

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 Single data type, an overflow error is generated.

Example

Dim sngMyNumber
If IsNumeric(sMyNumber) then
    sngMyNumber = CSng(sMyNumber)
End If

Programming Tips and Gotchas

  • If you need to use a floating-point number in VBScript, there is no reason to use a Single; use a Double instead. Generally, a Single is used because it offers better performance than a Double, but this is not true in VBScript. Not only is a Single not smaller than a Double in the VBScript implementation, but the processor also converts Singles to Doubles, performs any numeric operations, and then converts Doubles back to Singles.

  • Test that expression evaluates to a number by using the IsNumeric function.

Get VBScript in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.