posted on Saturday, July 12, 2008 9:38 PM by timbarcz

Formatting Output with ToString()

A coworker ran across the following and shared with me.

   1: Dim strpage
   2: strpage = pageNumber.ToString()
   3: If Len(strpage) = 1 Then
   4:     strpage = "000" & strpage
   5: ElseIf Len(strpage) = 2 Then
   6:     strpage = "00" & strpage
   7: ElseIf Len(strpage) = 3 Then
   8:     strpage = "0" & strpage
   9: End If 

The programmer is trying to ensure that the page number, when printed out, is always four characters long.  This is not the best way to write this code.  I thought I'd keep this post to myself but unfortunately this isn't the first time I've seen code like this, it is quite common.

The better way to write the above is:

   1: Dim strpage
   2: strpage = pagenumber.ToString("0000")

It's shorter, more concise, and easier to read.  Further the second example is more extensible.  If the requirements change to say the page number should be five characters, the first example must recompile.  The second example must be recompiled as well in it's current state, however the string "0000" could be moved to a configuration file somewhere and then wouldn't need to be.

Originally Posted At:  http://www.timbarcz.com/blog/FormattingOutputWithToString.aspx

(Update your feed readers to point to new address http://www.timbarcz.com/blog/)

Comments