C#中使用Console.WriteLine()限制输出保留两位小数
解决C#输出保留两位小数的问题
嘿,我懂你的困扰——要把小计、税额和总计都限制到百分位其实超简单,C#里有几种实用的字符串格式化方法能轻松实现,我给你一步步讲清楚:
方法1:直接用ToString("F2")格式化
这个方法最直接,对数值调用ToString并传入格式字符串"F2",就能自动保留两位小数,还会帮你处理四舍五入:
//Output results Console.WriteLine("Your subtotal is: $" + subTotal.ToString("F2")); Console.WriteLine("Your total tax is: $" + (taxTotal * subTotal).ToString("F2")); Console.WriteLine("Your grand total is: $" + grandTotal.ToString("F2"));
方法2:用字符串插值(推荐,代码更简洁直观)
C#的字符串插值$""语法可以直接在字符串里嵌入格式化规则,写起来更清爽:
//Output results Console.WriteLine($"Your subtotal is: ${subTotal:F2}"); Console.WriteLine($"Your total tax is: ${taxTotal * subTotal:F2}"); Console.WriteLine($"Your grand total is: ${grandTotal:F2}");
方法3:传统string.Format方式
如果你习惯老派的格式化写法,也可以用这个:
//Output results Console.WriteLine(string.Format("Your subtotal is: ${0:F2}", subTotal)); Console.WriteLine(string.Format("Your total tax is: ${0:F2}", taxTotal * subTotal)); Console.WriteLine(string.Format("Your grand total is: ${0:F2}", grandTotal));
这里的F2格式说明符的含义:
F代表固定点格式(Fixed-point),专门用来格式化小数2指定保留两位小数
所有方法都会自动处理四舍五入,比如计算出的税额是2.345的话,会自动变成2.35,完全符合你要的百分位要求。
另外给你个小建议:代码里的taxTotal其实是税率,改成taxRate会更直观;而且可以把税额提前计算好存起来,避免重复计算,让代码可读性更好。
附上修改后的完整代码(用最简洁的字符串插值方式):
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 taxRate = 0.07; // 变量名改成taxRate更贴合含义 double calculatedTax = 0; double grandTotal = 0; //Get the values from the user Console.WriteLine("Enter the total value of the first item: "); 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()); //Calculate totals subTotal = itemOne + itemTwo + itemThree + itemFour; calculatedTax = subTotal * taxRate; grandTotal = subTotal + calculatedTax; //Output results with two decimal places Console.WriteLine($"Your subtotal is: ${subTotal:F2}"); Console.WriteLine($"Your total tax is: ${calculatedTax:F2}"); Console.WriteLine($"Your grand total is: ${grandTotal:F2}"); Console.ReadLine(); } } }
这样运行起来,所有输出都会完美保留两位小数啦!
内容的提问来源于stack exchange,提问作者itz4blitz
相关产品推荐
相关产品推荐

