Format$ Function
Returns a String formatted according to instructions contained in a format expression.
Syntax
Format$(expression[, format[, firstdayofweek[, firstweekofyear]]])
Parameters
expression: Required. Any valid expression.format: Optional. A valid named or user-defined format expression.firstdayofweek: Optional. A constant that specifies the first day of the week.firstweekofyear: Optional. A constant that specifies the first week of the year.
Return Value
Returns a String containing the formatted representation of the expression. If format is omitted, Format$ returns a string similar to Str$.
Remarks
The Format$ function is one of the most versatile functions in VB6, allowing you to format numbers, dates, times, and strings according to predefined or custom format expressions.
You can use one of the predefined named formats or create user-defined formats with special characters that specify how the value should be displayed.
Named Numeric Formats
General Number: Display number with no thousand separatorCurrency: Display number with thousand separator and two decimal placesFixed: Display at least one digit to the left and two digits to the right of decimalStandard: Display number with thousand separatorPercent: Display number multiplied by 100 with percent signScientific: Use standard scientific notationYes/No: Display No if number is 0; otherwise display YesTrue/False: Display False if number is 0; otherwise display TrueOn/Off: Display Off if number is 0; otherwise display On
Named Date/Time Formats
General Date: Display date and/or timeLong Date: Display date according to long date formatMedium Date: Display date using medium date formatShort Date: Display date using short date formatLong Time: Display time using long time format (includes hours, minutes, seconds)Medium Time: Display time in 12-hour format using hours and minutes and AM/PMShort Time: Display time using 24-hour format (hh:mm)
User-Defined Number Format Characters
0: Digit placeholder. Display digit or zero#: Digit placeholder. Display digit or nothing.: Decimal placeholder%: Percentage placeholder,: Thousand separatorE- E+ e- e+: Scientific notation- + $ ( ): Display literal character\: Display next character as literal
User-Defined Date/Time Format Characters
c: Display date asdddddand time astttttd: Display day as number without leading zero (1-31)dd: Display day as number with leading zero (01-31)ddd: Display day as abbreviation (Sun-Sat)dddd: Display day as full name (Sunday-Saturday)m: Display month as number without leading zero (1-12)mm: Display month as number with leading zero (01-12)mmm: Display month as abbreviation (Jan-Dec)mmmm: Display month as full name (January-December)yy: Display year as 2-digit number (00-99)yyyy: Display year as 4-digit number (100-9999)h: Display hour as number without leading zero (0-23)hh: Display hour as number with leading zero (00-23)n: Display minute as number without leading zero (0-59)nn: Display minute as number with leading zero (00-59)s: Display second as number without leading zero (0-59)ss: Display second as number with leading zero (00-59)AM/PM: Use 12-hour clock and display uppercase AM/PM
User-Defined String Format Characters
@: Character placeholder. Display character or space&: Character placeholder. Display character or nothing<: Force lowercase>: Force uppercase
Typical Uses
Example 1: Formatting Currency
Dim amount As Double
amount = 1234.56
Text1.Text = Format$(amount, "Currency") ' "$1,234.56"
Example 2: Custom Number Format
Dim value As Double
value = 1234.5
result = Format$(value, "0000.00") ' "1234.50"
Example 3: Date Formatting
Dim today As Date
today = Now
dateStr = Format$(today, "Long Date")
Example 4: Custom Date Format
dateStr = Format$(Now, "yyyy-mm-dd") ' "2024-01-15"
Common Usage Patterns
Formatting as Percentage
Dim rate As Double
rate = 0.075
display = Format$(rate, "0.00%") ' "7.50%"
Zero-Padded Numbers
Dim id As Integer
id = 42
idStr = Format$(id, "000000") ' "000042"
Phone Number Formatting
Dim phone As String
phone = "5551234567"
formatted = Format$(phone, "(@@@) @@@-@@@@") ' "(555) 123-4567"
Time Formatting
Dim currentTime As Date
currentTime = Now
timeStr = Format$(currentTime, "hh:nn:ss AM/PM")
Scientific Notation
Dim bigNum As Double
bigNum = 12345678
sciStr = Format$(bigNum, "0.00E+00") ' "1.23E+07"
File Timestamp
filename = "backup_" & Format$(Now, "yyyymmdd_hhnnss") & ".dat"
Accounting Format
balance = Format$(amount, "#,##0.00;(#,##0.00)")
' Positive: "1,234.56"
' Negative: "(1,234.56)"
Leading Zeros for Dates
monthStr = Format$(Month(Date), "00") ' "01" to "12"
dayStr = Format$(Day(Date), "00") ' "01" to "31"
Conditional Formatting
' Format: positive;negative;zero
result = Format$(value, "+0.00;-0.00;Zero")
Uppercase/Lowercase Conversion
upperName = Format$("john doe", ">") ' "JOHN DOE"
lowerName = Format$("JOHN DOE", "<") ' "john doe"
Related Functions
Format: Variant version ofFormat$Str$: Converts a number to a stringCStr: Converts an expression to a stringFormatNumber: Formats a number with specific optionsFormatCurrency: Formats a number as currencyFormatDateTime: Formats a date/time valueFormatPercent: Formats a number as a percentage
Best Practices
- Use named formats for common formatting tasks (clearer intent)
- Cache format strings if using the same format repeatedly
- Test custom format strings with edge cases (zero, negative, very large/small)
- Use
@instead of&in string formats when you want spaces preserved - Remember that
mvsmmdepends on context (month vs minute) - Use four-digit years (
yyyy) to avoid Y2K-style issues - Consider locale settings when using named formats
- Use semicolons to specify different formats for positive, negative, and zero
- Escape literal characters with backslash or quotes when needed
- Be aware that
Format$returns a string - convert back if needed
Performance Considerations
- Named formats are slightly faster than complex user-defined formats
- Avoid calling
Format$in tight loops if possible (cache results) - For simple zero-padding,
String$+Right$may be faster Format$is slower than simple string concatenation- Consider using
FormatNumber,FormatCurrency, etc. for specific tasks
Locale Considerations
| Aspect | Behavior |
|---|---|
| Currency Symbol | Uses system locale currency symbol |
| Decimal Separator | Uses locale decimal separator (. or ,) |
| Thousand Separator | Uses locale thousand separator |
| Date Format | Named date formats use locale settings |
| Day/Month Names | Uses locale language for names |
| AM/PM Designators | Uses locale AM/PM strings |
| First Day of Week | Can be overridden with parameter |
| First Week of Year | Can be overridden with parameter |
Common Pitfalls
- Using
mfor minutes instead ofn(m means month) - Forgetting that
Format$always returns a string - Not escaping literal characters in format strings
- Assuming
#and0behave the same (they don't) - Using comma as decimal separator in code (always use period)
- Not handling empty strings or null values
- Forgetting that format strings are case-sensitive
- Using named formats that don't exist (causes error)
Limitations
- Cannot create truly custom named formats
- Limited control over locale-specific formatting
- No built-in format for ISO 8601 dates (must use
yyyy-mm-ddThh:nn:ss) - Cannot format arrays or objects directly
- Some format combinations may produce unexpected results
- Maximum string length limitations apply to output
- Cannot use for binary or hexadecimal display (use
Hex$orOct$)