Using Conversion Functions

Visual Basic provides several functions that convert data from one type to another using locale settings. However, some functions aren't locale-aware. Whenever possible, use the locale-aware functions to make your code transportable. This is especially important when you're converting strings to numbers or dates.

For example, the Str and Val functions always assume that a period is the decimal separator, but CStr, CDbl, CSng, CInt, and CLng use the current operating system settings to determine the decimal separator.

Special Considerations for Dates

Never type dates as strings in your code, because date formats aren't the same in every country. Even locale-aware conversion functions can process strings in ways you might not expect. For example, the following code behaves differently in different locales.


StartDate = "2/3/95"
NewDate = CDate(StartDate)

When run in an English/United States locale, NewDate contains a value equivalent to February 3, 1995; in an English/Australia locale, NewDate contains a value equivalent to March 2, 1995. This behavior is a potential source of error when you're programming, but it's very useful for processing user input from a dialog box. CDate converts the user's text into the date that the user intends.

However, as the programmer, you should always code dates as literals — such as #2/3/95# — so that Visual Basic recognizes the exact date you intend. For example, in the following code, NewDate contains a value equivalent to either February 3, 1995, or March 2, 1995, depending on the locale of the programmer, but not the locale of the user. The date is the same for all users wherever the code is run.


StartDate = #2/3/95#
NewDate = CDate(StartDate)

The date literal is interpreted in the context of the programmer's locale.

Special Considerations for Currencies

Similarly, never store a currency value as a string that includes a currency symbol, because the currency symbol varies according to locale. For example, the following code doesn't run in any locale except those where the dollar sign ($) is the currency symbol.


Money = "$1.22"
NewMoney = CCur(Money)

Instead, store a currency value as a decimal number, as shown in the following example. (This example assumes that the period is the decimal separator in the programmer's locale, but the code runs correctly no matter what the decimal separator is in the user's locale.)


Money = 1.22
NewMoney = CCur(Money)