How to Right Justify Numbers Using Format$

Last reviewed: June 21, 1995
Article ID: Q95945
The information in this article applies to:

- Standard and Professional Editions of Microsoft Visual Basic for

  Windows, versions 2.0 and 3.0

SUMMARY

NOTE: The technique described in this article works only with monospace fonts like Courier New, not proportional fonts like Times New Roman.

Use the following two-step process to right justify numbers in a string by using the format$ function:

  1. Format the number into a string by using the usual numeric conversion characters (0 # . ,).

  2. Format the resulting string by using a format string consisting of a number of @ characters equal to the length of the format string used in step 1.

The following example Sub procedure formats several numbers using the seven character formats $##0.00 and @@@@@@@:

   Sub Form_Click ()
      Print "|" + Format$(Format$(1.5, "$##0.00"), "@@@@@@@") + "|"
      Print "|" + Format$(Format$(12.5, "$##0.00"), "@@@@@@@") + "|"
      Print "|" + Format$(Format$(123.5, "$##0.00"), "@@@@@@@") + "|"
   End Sub

Here is the output:

   |  $1.50|
   | $12.50|
   |$123.50|

MORE INFORMATION

You can automatically generate the @ format string by using Len and String$ as in this example:

   Function rFormat (value As Variant, fmt As String) As Variant
      rFormat = Format(Format(value, fmt), String$(Len(fmt), "@"))
   End Function


Additional reference words: 2.00 3.00 align alignment right-justify
KBCategory: kbenv kbprg
KBSubcategory: EnvtRun


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: June 21, 1995
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.