Name
CSng Function
Named Arguments
No
Syntax
CSng(expression)-
expression Use: Required
Data Type: Numeric or String
The range of
expressionis -3.402823E38 to -1.401298E-45 for negative values, and 1.401298E-45 to 3.402823E38 for positive values.
Return Value
expression cast as a Single data type
Description
Returns a single-precision number
Rules at a Glance
expressionmust evaluate to a numeric value; otherwise, a type-mismatch error is generated.If the value of
expressionis outside the range of the Double data type, an overflow error is generated.
Example
Dim sngMyNumber As Single
If IsNumeric(sMyNumber) Then
sngMyNumber = CSng(sMyNumber)
End IfProgramming Tips and Gotchas
You can use
IsNumericto test an expression before passing it toCSng.When converting a string representation of a number to a numeric, you should use the data type conversion functions—such as
CSng—instead ofVal, because the data type conversion functions take into account the computer’s regional settings. The thousands separator is the most important of these regional settings. For example, if the value ofexpressionis the string 1,234.987,CSngconverts it to 1234.987, whileValincorrectly converts it to 1.Like most of the conversion functions,
CSngis not actually a function in the Microsoft.VisualBasic namespace. Instead, it is similar to a Visual C++ macro; the compiler translates the function call into inline code.
See Also
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access