首页 > 解决方案 > 在 c# 中使用 console.writeline() 将输出限制为百分之一

问题描述

我看过类似的帖子,但我找不到对我来说有意义的线程。这是我在上课的第二周项目。我想限制小计的输出。总税额,计算完成后总计到百分之一。但我无法弄清楚我需要如何修改现有的 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();

        }
    }
}

我感谢任何人对此的意见。问候!

标签: c#rounding

解决方案


使用字符串插值:

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

或使用 String.Format

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

“固定”格式 (Fn) 指定小数点后的位数,F1 表示 1 位,F2 表示 2 位等。


推荐阅读