【问题标题】:Dollar Amounts in C#C# 中的美元金额
【发布时间】:2016-10-07 03:47:25
【问题描述】:

我浏览了其他一些帖子,但似乎没有任何帮助。所以我想要得到的是一个代码,它可以读出当前余额,前面有一个短语,还有一个美元金额。而不是打印美元符号,而是打印{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();
        }
    }
}

【问题讨论】:

    标签: c# string-formatting currency


    【解决方案1】:
    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} ";
    

    【讨论】:

    • 如果不需要抓取字符串,只是打算直接输出到控制台,也可以使用Console.WriteLine("Your account currently contains this much money: {0:C} ", TotalAmount);
    • 我尝试了第一个,它告诉我“;预期”和“预期方法名称”在 YourBalance 和“无法将方法组'格式'转换为非委托类型'字符串'。你打算调用方法?”关于.Format
    • 哦,我没想到,我不需要保留字符串,只需输出。感谢您的帮助
    【解决方案2】:

    你非常接近!你需要使用string.Format():

    string YourBalance = string.Format(
        "Your account currently contains this much money: {0:C} ", TotalAmount);
    

    {0:C} 语法在Format 方法的上下文之外没有任何意义。

    这是您示例中的一个工作小提琴:Fiddle

    【讨论】:

      【解决方案3】:

      我是否错误地使用了 {0:C}?

      是的,你是。您只是连接字符串和TotalAmount。因此,即使您使用了货币格式说明符 ({0:C}),货币金额也不会替换说明符。

      你需要使用String.Format(),像这样:

      string YourBalance = String.Format("Your account currently contains this much money: {0:C}", TotalAmount);
      

      【讨论】:

        【解决方案4】:

        你可以用这个...

        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();
                }
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2020-10-09
          • 1970-01-01
          • 2016-10-16
          • 2017-01-18
          • 2011-04-13
          • 1970-01-01
          • 1970-01-01
          • 2011-07-31
          • 2018-02-13
          相关资源
          最近更新 更多