Export (0) Print
Expand All
2 out of 2 rated this helpful - Rate this topic

Conversions Between Strings and Other Types

You can convert a numeric, Boolean, or date/time value to a String. You can also convert in the reverse direction — from a string value to numeric, Boolean, or Date — provided the contents of the string can be interpreted as a valid value of the destination data type. If they cannot, a run-time error occurs.

The conversions for all these assignments, in either direction, are narrowing conversions. You should use the type conversion keywords (CStr, CShort, CInt, CLng, CDec, CSng, CDbl, CBool, CDate, and CType). The Format and Val functions give you additional control over conversions between strings and numbers.

Conversion of Numbers to Strings

You can use the Format function to convert a number to a formatted string, which can include not only the appropriate digits but also formatting symbols such as a currency sign (such as $), thousands separators or digit grouping symbols (such as ,), and a decimal separator (such as .). Format automatically uses the appropriate symbols according to the Regional Options settings specified in the Windows Control Panel.

Note that the concatenation (&) operator can convert a number to a string implicitly, as shown in the following example:

Str = "The total count is " & Count    ' Count is converted to String.

Conversion of Strings to Numbers

You can use the Val function to explicitly convert the digits in a string to a number. Val reads the string until it encounters a character other than a digit, space, tab, line feed, or period. The sequences "&O" and "&H" alter the base of the number system and terminate the scanning. Until it stops reading, Val converts all appropriate characters to a numeric value. For example, the following statement returns the value 141.8:

Val(" 14 1.8 miles")

When Visual Basic converts a string to a numeric value, it uses the Regional Options settings specified in the Windows Control Panel to interpret the thousands separator, decimal separator, and currency symbol. This means that a conversion might succeed under one setting but not another. For example, "$14.20" is acceptable in the English (United States) locale but not in any French locale.

See Also

Widening and Narrowing Conversions | Implicit and Explicit Conversions | Value Changes During Conversions

Typeless Programming

Data Type Summary | Type Conversion Functions | Format Function | Val Function | Introduction to International Applications in Visual Basic and Visual C#

Did you find this helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2014 Microsoft. All rights reserved.