2013-04-16 55 views
2

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

回答

11

我所試圖做的是形式按月支付價值爲2位小數,並添加「$」符號。

聽起來像你想要使用currency format specifier

Console.WriteLine("The amount of the monthly payment is: {0:c}", monthlyPayment); 

那當然不會總是使用美元符號 - 它會使用線程當前文化的貨幣符號。您始終可以明確指定CultureInfo.InvariantCulture

但是,我強烈建議您而不是使用double貨幣值。改爲使用decimal

+1

+1指出小數格式在貨幣價值方面比雙倍更適合。 (對於正確答案:D) – keyboardP

0

可以使用Math.Round()功能:

double inputNumber = 90.0001; 
string outputNumber = "$" + Math.Round(inputNumber, 2).ToString(); 
0

要使用2位小數,你可以使用:

Console.WriteLine("The amount of the monthly payment is: "$ " + Math.Round(monthlyPayment,2)); 
相關問題