CSng - VBScript
Overview
The CSng command in VB Script is a conversion function that changes a string to a Single-precision floating-point number. It is primarily used to convert numeric strings entered by the user or stored in variables.
Syntax
CSng(expression)
where:
- expression is a numeric string that needs to be converted.
Options/Flags
This command does not support any options or flags.
Examples
- Convert a string to a floating-point number:
Dim strNumber = "123.45"
Dim fltNumber = CSng(strNumber)
- Extract a numeric value from a string:
Dim strInput = "Total Cost: $123.45"
Dim strSubstring = Mid(strInput, 11)
Dim fltCost = CSng(strSubstring)
Common Issues
- Ensure that the string to be converted contains a valid numeric value. If it contains non-numeric characters or improper formatting, an error will occur.
- Handle potential overflow or underflow conditions when converting large or small numbers.
Integration
CSng can be combined with other VB Script commands to perform complex data conversions:
- Use Val to first convert the string to a Variant, and then use CSng to convert it to a floating-point number.
Dim strNumber = "123.45"
Dim fltNumber = CSng(Val(strNumber))
- Use FormatNumber to format the converted floating-point number as a currency string.
Dim fltNumber = 123.45
Dim strCurrency = FormatNumber(fltNumber, 2) ' 2 decimal places
Related Commands
- CBool: Converts a string to a Boolean value.
- CDate: Converts a string to a Date value.
- CInt: Converts a string to an Integer value.
- CLng: Converts a string to a Long integer value.
- Val: Converts a string to a Variant.