使用c#中的console.writeline()将输出限制为百分位

时间:2018-05-14 19:03:57

标签: c# rounding

我已经看过类似的帖子了,但我找不到能够理解这个问题的帖子。这是我正在上课的第二周项目。我想限制小计的输出。计算完成后,总税额和总计百分之一。但我无法弄清楚如何修改现有的console.writeline()语句。

using System;

namespace Week_2_CIS_Lab_Assignment
{
    class Program
    {
        static void Main(string[] args)
        {
            //Declare Variables
            double itemOne = 0;
            double itemTwo = 0;
            double itemThree = 0;
            double itemFour = 0;
            double subTotal = 0;
            const double taxTotal = 0.07;
            double grandTotal = 0;

            //Get the values from the user
            Console.WriteLine("Enter the total value of the first time: ");
            itemOne = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Enter the total value of the second item: ");
            itemTwo = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Enter the total value of the third item: ");
            itemThree = Convert.ToDouble(Console.ReadLine());
            Console.WriteLine("Enter the value of the fourth item: ");
            itemFour = Convert.ToDouble(Console.ReadLine());

            //internal stuffz
            subTotal = itemOne + itemTwo + itemThree + itemFour;
            grandTotal = subTotal + (subTotal * taxTotal);

            //Output results
            Console.WriteLine("Your subtotal is: $" + subTotal);
            Console.WriteLine("Your total tax is: $" + taxTotal * subTotal);
            Console.WriteLine("Your grand total is: $" + grandTotal);
            Console.ReadLine();

        }
    }
}

我感谢任何人对此的投入。此致!

2 个答案:

答案 0 :(得分:0)

使用字符串插值:

double d = 1.23;
Console.WriteLine($"{d:F2}");

或使用String.Format

Decimal d = 1.23M;
Console.WriteLine(string.Format("{0:F2}", d));

is"已修复" format(Fn)指定小数点后的位数,F1表示1位数字,F2表示2位数字等。

答案 1 :(得分:-1)

            Console.WriteLine("Your total tax is: $" + totalTax.ToString("F2"));
        Console.WriteLine("Your grand total is: $" + grandTotal.ToString("F2"));
似乎要做的伎俩!谢谢!