|
Formatting Numbers using FormatNumber() Function (VB.Net) |
|
|
Written by: Justin Rich
Formatting Numbers using FormatNumber() FunctionFormatting numbers in programming becomes a very important task, especially when dealing with percentages, currency, and dates. For more about formatting dates, visit this article: http://www.stellarpc.com/articles/board.aspx?id=7
First, I'm going to start with general number formatting and the FormatNumber function. The return value of this function is the number formatted in the manner specified in the parameters being passed. What are these parameters? Here is what it looks like:
FormatNumber(value [, trailing digits] [, leading digit] [, parentheses] [, group digits]) All of the parameters for this function are optional, so you can simply call a FormatNumber(9876.54321) and you will get back 9,876.54 as the return. This is good for quick & simple 2 decimal point return with commas because 2 trailing digits is the default.
To specify the decimals, we'll pass that number in the trailing digits parameter: FormatNumber(9876.54321, 6) and get a return of 9,876.543210 because we requested 6 trailing digits.
In the leading digits column, we're passing a boolean value of True or False to say if you want leading digits to show up... so when your number is less than 1, you're specifying if you want it to appear as 0.99 or just .99. True will print the 0, False will not. True is the default, so not specifying will always generate the 0.
In the parentheses parameter, you're specifying a boolean value of whether or not you want parentheses around negative numbers or not. If you don't specify it, it's automatically defaluted to False, so you have to say True to get it to work. Parentheses are used commonly on balance sheets for money values. Calling FormatNumber(-9876.54321,,,True) will return (9,876.54) and without the True will return -9876.54. Make a note of the fact that I still had to enter the commas in my Function call for the other 2 parameters even though I didn't specify values.
Finally, to turn off the commas in the number, we use the group digits paramter. By default, it's always True, which means that it's grouping the digits together and using commas to show the grouping. Turning this to false will turn the comma grouping off. For example: FormatNumber(9876.54321,,,,False) will return 9876.54 and the comma between the 9 & 8 will not print.
|
|
|
|
|
|