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

4 回答 4

11

我要做的是将每月付款值格式化为小数点后 2 位并添加“$”符号。

听起来您想使用货币格式说明符

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

当然,这并不总是使用美元符号 - 它会使用线程当前文化的货币符号。您始终可以CultureInfo.InvariantCulture明确指定。

但是,我强烈建议您不要使用double货币价值。改为使用decimal

于 2013-04-16T19:06:18.197 回答
1

来自 MSDN:标准数字格式字符串 (查找“货币(“C”)格式说明符)

Console.WriteLine("月付金额为:{0:C2} ",monthlyPayment);

于 2013-04-16T19:14:00.117 回答
0

要使用 2 位小数,您可以使用:

Console.WriteLine("The amount of the monthly payment is: "$ " + Math.Round(monthlyPayment,2));
于 2013-04-16T19:12:15.317 回答
0

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

double inputNumber = 90.0001;
string outputNumber = "$" + Math.Round(inputNumber, 2).ToString();
于 2013-04-16T19:06:37.090 回答