[英]Limiting output to hundredths place with console.writeline() in c#
我已经看到过类似的帖子,但是找不到适合我这个问题的主题。 这是我上课的第二个星期的项目。 我想限制小计的输出。 计算完成后,税收总额和总计百分位。 但是我不知道如何修改现有的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();
}
}
}
感谢任何人对此的投入。 问候!
使用字符串插值:
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位,依此类推。
Console.WriteLine("Your total tax is: $" + totalTax.ToString("F2"));
Console.WriteLine("Your grand total is: $" + grandTotal.ToString("F2"));
似乎可以解决问题! 谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.