C# 中的美元金额
Dollar Amounts in C#
我浏览了其他一些帖子,但似乎没有任何帮助。所以我想要得到的是一个代码,它可以读出当前余额,前面有一个短语,还有一个美元金额。与其打印美元符号,不如打印 {0:C}
。我是不是用错了{0:C}
?
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
double TotalAmount;
TotalAmount = 300.7 + 75.60;
string YourBalance = "Your account currently contains this much money: {0:C} " + TotalAmount;
Console.WriteLine(YourBalance);
Console.ReadLine();
}
}
}
Am I using {0:C} incorrectly?
是的,你是。您只是连接字符串和 TotalAmount
。因此,即使您使用货币格式说明符 ({0:C}
),货币金额也不会替换说明符。
你需要使用String.Format()
,像这样:
string YourBalance = String.Format("Your account currently contains this much money: {0:C}", TotalAmount);
string YourBalance =
string.Format("Your account currently contains this much money: {0:C} ",TotalAmount);
或在 C# 6.0+ 中使用字符串插值
string YourBalance = $"Your account currently contains this much money: {TotalAmount:C} ";
你非常接近!您需要使用 string.Format()
:
string YourBalance = string.Format(
"Your account currently contains this much money: {0:C} ", TotalAmount);
{0:C}
语法在 Format 方法的上下文之外没有任何意义。
这是您示例中的有效 fiddle:Fiddle
你可以使用这个...
using System.Globalization;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
double TotalAmount;
TotalAmount = 300.7 + 75.60;
string YourBalance = "Your account currently contains this much money: " +
string.Format(new CultureInfo("en-US"), "{0:C}",TotalAmount);
Console.WriteLine(YourBalance);
Console.ReadLine();
}
}
}
我浏览了其他一些帖子,但似乎没有任何帮助。所以我想要得到的是一个代码,它可以读出当前余额,前面有一个短语,还有一个美元金额。与其打印美元符号,不如打印 {0:C}
。我是不是用错了{0:C}
?
namespace ConsoleApplication7
{
class Program
{
static void Main(string[] args)
{
double TotalAmount;
TotalAmount = 300.7 + 75.60;
string YourBalance = "Your account currently contains this much money: {0:C} " + TotalAmount;
Console.WriteLine(YourBalance);
Console.ReadLine();
}
}
}
Am I using {0:C} incorrectly?
是的,你是。您只是连接字符串和 TotalAmount
。因此,即使您使用货币格式说明符 ({0:C}
),货币金额也不会替换说明符。
你需要使用String.Format()
,像这样:
string YourBalance = String.Format("Your account currently contains this much money: {0:C}", TotalAmount);
string YourBalance =
string.Format("Your account currently contains this much money: {0:C} ",TotalAmount);
或在 C# 6.0+ 中使用字符串插值
string YourBalance = $"Your account currently contains this much money: {TotalAmount:C} ";
你非常接近!您需要使用 string.Format()
:
string YourBalance = string.Format(
"Your account currently contains this much money: {0:C} ", TotalAmount);
{0:C}
语法在 Format 方法的上下文之外没有任何意义。
这是您示例中的有效 fiddle:Fiddle
你可以使用这个...
using System.Globalization;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
double TotalAmount;
TotalAmount = 300.7 + 75.60;
string YourBalance = "Your account currently contains this much money: " +
string.Format(new CultureInfo("en-US"), "{0:C}",TotalAmount);
Console.WriteLine(YourBalance);
Console.ReadLine();
}
}
}