Format 函式

更新:2007 年 11 月

傳回依據包含於格式 String 運算式中的指令所格式化的字串。

Public Shared Function Format( _
   ByVal Expression As Object, _
   Optional ByVal Style As String = "" _
) As String

參數

  • Expression
    必要項。任何有效的運算式。

  • Style
    選擇項。有效的具名或使用者定義的格式 String 運算式。

設定

如需如何建立 Style 引數的詳細資訊,請參閱下列的適當主題:

若要格式化

請執行

數字

使用預先定義的數值格式或建立使用者定義數值格式

日期和時間

使用預先定義的日期/時間格式或建立使用者定義日期/時間格式

日期和時間序號

使用日期與時間格式或數值格式。

雖然這個函式能夠偵測地區設定,但是如果您嘗試在未指定 Style 的情況下格式化數值,則 Format 函式會提供類似於 Str 函式的功能。但是,使用 Format 函式格式化成為字串的正數數值不包括為數值正負號保留的句首空格,使用 Str 函式所轉換的正數會保留句首空格。

備註

如果您正在格式化尚未當地語系化的數值字串,您應使用使用者定義數值格式以確保可獲得所需格式。

String.Format 方法也提供同樣的功能。

範例

本範例呈現使用 String 格式及使用者定義格式來格式化數值的各種 Format 函式用法。就日期分隔符號 (/)、時間分隔符號 (:) 及 AM/PM 指示器 (Indicator) (t 和 tt) 而論,系統所顯示的實際格式輸出取決於程式碼正在使用的地區設定 (Locale)。當在開發環境中顯示時間與日期時,會使用程式碼地區設定的簡短時間格式及簡短日期格式。

注意事項:

若為使用 24 小時制的地區設定,AM/PM 指示器 (t 和 tt) 不會顯示任何內容。

Dim TestDateTime As Date = #1/27/2001 5:04:23 PM#
Dim TestStr As String
' Returns current system time in the system-defined long time format.
TestStr = Format(Now(), "Long Time")
' Returns current system date in the system-defined long date format.
TestStr = Format(Now(), "Long Date")
' Also returns current system date in the system-defined long date 
' format, using the single letter code for the format.
TestStr = Format(Now(), "D")

' Returns the value of TestDateTime in user-defined date/time formats.
' Returns "5:4:23".
TestStr = Format(TestDateTime, "h:m:s")
' Returns "05:04:23 PM".
TestStr = Format(TestDateTime, "hh:mm:ss tt")
' Returns "Saturday, Jan 27 2001".
TestStr = Format(TestDateTime, "dddd, MMM d yyyy")
' Returns "17:04:23".
TestStr = Format(TestDateTime, "HH:mm:ss")
' Returns "23".
TestStr = Format(23)

' User-defined numeric formats.
' Returns "5,459.40".
TestStr = Format(5459.4, "##,##0.00")
' Returns "334.90".
TestStr = Format(334.9, "###0.00")
' Returns "500.00%".
TestStr = Format(5, "0.00%")

需求

命名空間 (Namespace)︰Microsoft.VisualBasic

模組:Strings

組件 (Assembly):Visual Basic Runtime Library (在 Microsoft.VisualBasic.dll 中)

請參閱

參考

字串操作摘要

不同數值的不同格式 (Format 函式)

預先定義的日期/時間格式 (Format 函式)

預先定義的數值格式 (Format 函式)

Str 函式

型別轉換函式

使用者定義日期/時間格式 (Format 函式)

使用者定義數值格式 (Format 函式)

Format