在 C# 中將字串格式設定為貨幣格式
Muhammad Maisam Abbas
2024年2月16日
Csharp
Csharp String
本教程將討論在 C# 中將字串變數格式化為貨幣格式的方法。
在 C# 中使用 String.Format() 方法將字串格式化為貨幣
String.Format() 方法用 C# 格式化字串。我們可以使用 String.Format() 方法中的 {0:C} 格式說明符將字串變數轉換為貨幣格式。以下程式碼示例向我們展示瞭如何使用 C# 中的 String.Format() 方法將字串格式化為貨幣格式。
using System;
namespace string_to_currency {
class Program {
static void Main(string[] args) {
decimal money = 1234.56M;
string mstring = String.Format("{0:C}", money);
Console.WriteLine(mstring);
}
}
}
輸出:
$1,234.56
在上面的程式碼中,我們使用 C# 中的 String.Format() 方法將十進位制變數 money 轉換為貨幣格式的字串變數 mstring。我們使用格式說明符 {0:C} 將 money 格式化為貨幣格式的字串。
在 C# 中使用 ToString() 方法將字串格式化為貨幣
ToString() 方法用於將任何資料型別轉換為 C# 中的字串變數。我們可以使用 C 字串格式說明符以貨幣格式格式化結果字串變數。以下程式碼示例向我們展示瞭如何使用 C# 中的 ToString() 方法將字串格式化為貨幣格式。
using System;
namespace string_to_currency {
class Program {
static void Main(string[] args) {
decimal money = 1234.56M;
string mstring = money.ToString("C");
Console.WriteLine(mstring);
}
}
}
輸出:
$1,234.56
在上面的程式碼中,我們使用 C# 中的 ToString() 方法將貨幣格式的十進位制變數 money 轉換為字串變數 mstring。我們在 ToString() 方法內部使用了格式說明符 C,以貨幣格式的字串格式化 money。
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Maisam is a highly skilled and motivated Data Scientist. He has over 4 years of experience with Python programming language. He loves solving complex problems and sharing his results on the internet.
LinkedIn