Thursday, February 28, 2008

String formatting

As promised, here are the notes on section 3.5 Input/Output (by Alex)
________________________________________________________________

Formatting:

There are various ways of formatting output in VB. One way is with some more built in functions:

FormatNumber( number or variable to format, places to round )

This will take a number and format it to a certain number of decimal places. Below is an example of using this function:

FormatNumber( 12345.628, 2) will evaluate to 12,345.63
FormatNumber( 444212.333, 0) will evaluate to 444,212

FormatCurrency( number or variable to format, places to round )

This will take a number and format it to a currency value to a certain number of decimal places. Below is an example of using this function:

FormatCurrency( 12345.628, 2) will evaluate to $12,345.63
FormatCurrency( 345.4426, 3) will evaluate to $345.443

FormatPercent( number or variable to format, places to round )

This will take a number and format it to a percentage value to a certain number of decimal places. Below is an example of using this function:

FormatPercent( 0.185, 2) will evaluate to 18.50%


Now, notice with the Percent and Currency function, the appropriate symbol is added to the outputted value. There are other Format functions available but these are again the most frequently used.

To format a string output, you use something called zones. Since I cannot draw once again, I will have to refer you to the textbook example 1 in section 3.5. But here is how the formatting variable will look:

Dim fmtStr As String
fmtStr = "{0,15}{1,8}{2,9}"

Here is how that looks. Notice that there is no spaces between the curly braces inside the string. Also notice each section has two numeric values. The first value is the zone number so in the above example they would be 0...1...2. The second value is the number of spaces to format so these would be 15...8...9. Here is how to use it in a program:

lstOut.Items.Add( String.Format( fmtStr,item 1, item 2, item 3 ) )

The number of items in the above line needs to match the number of zones you declare in the formatting string. Again, see example 1 for the full diagram as well as a short program.

No comments: