Format 函式請參閱
不同數值的不同格式 (Format 函式) | 預先定義的日期/時間格式 (Format 函式) | 預先定義的數值格式 (Format 函式) | Str 函式 | 型別轉換函式 | 使用者定義日期/時間格式 (Format 函式) | 使用者定義數值格式 (Format 函式) | String.Format 方法
需求
命名空間:Microsoft.VisualBasic
模組:Strings
組件 (Assembly):Microsoft Visual Basic .NET Runtime (在 Microsoft.VisualBasic.dll 中)
傳回依據包含於格式 String 運算式中的指令所格式化的字串 (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)。當在開發環境中顯示時間與日期時,會使用程式碼地區設定的簡短時間格式及簡短日期格式。
Dim MyDateTime As Date = #1/27/2001 5:04:23 PM#
Dim MyStr As String
' Returns current system time in the system-defined long time format.
MyStr = Format(Now(), "Long Time")
' Returns current system date in the system-defined long date format.
MyStr = Format(Now(), "Long Date")
' Also returns current system date in the system-defined long date
' format, using the single letter code for the format.
MyStr = Format(Now(), "D")
' Returns the value of MyDateTime in user-defined date/time formats.
MyStr = Format(MyDateTime, "h:m:s") ' Returns "5:4:23".
MyStr = Format(MyDateTime, "hh:mm:ss tt") ' Returns "05:04:23 PM".
MyStr = Format(MyDateTime, "dddd, MMM d yyyy") ' Returns "Saturday,
' Jan 27 2001".
MyStr = Format(MyDateTime, "HH:mm:ss") ' Returns "17:04:23"
MyStr = Format(23) ' Returns "23".
' User-defined numeric formats.
MyStr = Format(5459.4, "##,##0.00") ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00") ' Returns "334.90".