Simple Formatting


Use the CStr function to generally convert any type to a String. The returned value is dependent upon the input data type. Boolean values convert to the text "True" or "False." Dates convert to the short date format used by the system. Numbers are converted to a string representation of the number. See Listing 15 .

Listing 15: Output from CStr is locale specific; this is English (USA).
start example
 Dim n As Long, d As Double, b As Boolean n = 999999999 : d = EXP(1.0) : b = False Print "X" & CStr(b)  'XFalse Print "X" & CStr(n)  'X999999999 Print "X" & CStr(d)  'X2.71828182845904 Print "X" & CStr(Now)'X08/14/2003 20:39:49 
end example
 

The CStr function performs simple number formatting with knowledge of the current locale. Simple conversion of a number to a string is done with Str. Although the Str function is designed to deal specifically with numeric values, the output is very similar to CStr. When the Str function converts a number to a string, a leading space is always included for the sign of the number. A negative number includes the minus sign, and no leading empty space is present. A non-negative number, on the other hand, includes a leading empty space. The output of Str is not locale specific; a period is always used as the decimal separator. See Listing 16 .

Listing 16: Output from Str is not dependent upon locale.
start example
 Dim n As Long, d As Double, b As Boolean n = 999999999 : d = EXP(1.0) : b = False Print "X" & Str(b)  'XFalse Print "X" & Str(n)  'X 999999999 Print "X" & Str(d)  'X 2.71828182845904 Print "X" & Str(Now)'X08/14/2003 20:39:49 
end example
 

The output from the code in Listing 15 and Listing 16 is the same except for a leading space in front of the non-negative numbers. If you run the code using a different locale, such as Germany, the output changes forListing 15 but not Listing 16.

Tip  

There is little reason to use Str rather than CStr. Str may run a bit faster, but CStr knows about your current locale.

To demonstrate that CStr is locale specific, I changed my locale to German (Germany) and then ran the code in Listing 15 again. Listing 17 shows that the decimal is now expressed as a comma and that the date is now expressed as MM.DD.YYYY.

Listing 17: Output from CStr is locale specific; this is German (Germany).
start example
 Dim n As Long, d As Double, b As Boolean n = 999999999 : d = EXP(1.0) : b = False Print "X" & CStr(b)  'XFalse Print "X" & CStr(n)  'X999999999 Print "X" & CStr(d)  'X2,71828182845904 Print "X" & CStr(Now)'X14.08.2003 20:39:49 
end example
 



OpenOffice.org Macros Explained
OpenOffice.org Macros Explained
ISBN: 1930919514
EAN: 2147483647
Year: 2004
Pages: 203

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net