[英]How to format output to two decimal places and '$' symbol in C#?
C#語言的新手,我剛剛創建了一個貸款抵押計算器,我在下面格式化我的代碼時遇到了問題。 我想要做的是將每月付款值格式化為2位小數並添加“$”符號。 任何幫助,將不勝感激。 謝謝!
我的原則金額的示例輸入:
//User input for Principle amount in dollars
Console.Write("Enter the loan amount, in dollars(0000.00): ");
principleInput = Console.ReadLine();
principle = double.Parse(principleInput);
//Prompt the user to reenter any illegal input
if (principle < 0)
{
Console.WriteLine("The value for the mortgage cannot be a negative value");
principle = 0;
}
//Calculate the monthly payment
double loanM = (interest / 1200.0);
double numberMonths = years * 12;
double negNumberMonths = 0 - numberMonths;
double monthlyPayment = principle * loanM / (1 - System.Math.Pow((1 + loanM), negNumberMonths));
//Output the result of the monthly payment
Console.WriteLine("The amount of the monthly payment is: " + monthlyPayment);
Console.WriteLine();
Console.WriteLine("Press the Enter key to end. . .");
Console.Read();
我想要做的是將每月付款值格式化為2位小數並添加“$”符號。
聽起來你想使用貨幣格式說明符 。
Console.WriteLine("The amount of the monthly payment is: {0:c}", monthlyPayment);
當然,這並不總是使用美元符號 - 它將使用貨幣符號作為線程的當前文化。 您始終可以顯式指定CultureInfo.InvariantCulture
。
但是,我強烈建議您不要使用double
貨幣值。 請改用decimal
。
來自MSDN:標准數字格式字符串 (查找'貨幣(“C”)格式說明符')
Console.WriteLine(“每月付款金額為:{0:C2}”,monthlyPayment);
您可以使用Math.Round()
函數:
double inputNumber = 90.0001;
string outputNumber = "$" + Math.Round(inputNumber, 2).ToString();
要使用2位小數,您可以使用:
Console.WriteLine("The amount of the monthly payment is: "$ " + Math.Round(monthlyPayment,2));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.