gpt4 book ai didi

c# - 如何在 C# 中将输出格式化为两位小数和 '$' 符号?

转载 作者:行者123 更新时间:2023-11-30 19:05:56 25 4
gpt4 key购买 nike

C# 语言新手和我刚刚创建了一个贷款抵押计算器,但我在格式化下面的代码时遇到了问题。我想要做的是将每月付款值格式化为小数点后两位并添加“$”符号。任何帮助,将不胜感激。谢谢!

我的本​​金金额输入示例:

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

最佳答案

What I am trying to do is format the monthly payment value to 2 decimal places and add the '$' symbol.

听起来您想使用 currency format specifier .

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

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

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

关于c# - 如何在 C# 中将输出格式化为两位小数和 '$' 符号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045019/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com