简体   繁体   中英

How to format output to two decimal places and '$' symbol in C#?

Newbie to the C# language and I just finished creating a loan mortgage calculator and I am having trouble formatting my code below. What I am trying to do is format the monthly payment value to 2 decimal places and add the '$' symbol. Any help would be appreciated. Thanks!

Example input for my principle amount:

//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.

It sounds like you want to use the currency format specifier .

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

That won't always use the dollar symbol of course - it will use the currency symbol for the thread's current culture. You can always specify CultureInfo.InvariantCulture explicitly.

However, I'd strongly advise you not to use double for currency values. Use decimal instead.

From MSDN: Standard Numeric Format Strings (look for 'The Currency ("C") Format Specifier')

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

You can use the Math.Round() function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM