我浏览了一些其他帖子,但似乎没有任何帮助。所以我想要的是一个代码,用一个美元金额读出当前的余额,前面有一个短语。而不是打印美元符号打印{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();
}
}
}
答案 0 :(得分:6)
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} ";
答案 1 :(得分:1)
我是否错误地使用{0:C}?
是的,你是。您只是将字符串与TotalAmount
连接起来。因此,即使您使用货币格式说明符({0:C}
),货币金额也不会替换说明符。
您需要使用String.Format()
,如下所示:
string YourBalance = String.Format("Your account currently contains this much money: {0:C}", TotalAmount);
答案 2 :(得分:1)
你非常接近!您需要使用string.Format()
:
string YourBalance = string.Format(
"Your account currently contains this much money: {0:C} ", TotalAmount);
{0:C}
语法并不代表Format方法的上下文之外的任何内容。
以下是您示例中的工作小提琴:Fiddle
答案 3 :(得分:0)
您可以使用此...
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();
}
}
}