簡體   English   中英

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

我是否錯誤地使用了 {0:C}?

是的,你是。 您只是連接字符串和TotalAmount 因此,即使您使用了貨幣格式說明符 ( {0:C} ),貨幣金額也不會替換說明符。

您需要使用String.Format() ,如下所示:

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

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

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

{0:C}語法在Format方法的上下文之外沒有任何意義。

這是您示例中的一個工作小提琴: 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();
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM