c# - 在 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();
}
}
}
我感谢任何人对此的意见。问候!
解决方案
使用字符串插值:
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 位等。
推荐阅读
- asp.net-mvc - DropzoneJS:调整文件大小后的图像尺寸
- node.js - NODE.JS:如果我尝试访问子文件夹,404 页面的 CSS 会中断
- python - 有没有办法在 Python 中的字符串中插入一个额外的“\”?
- android - 无法使用 xamarin 表单在 android 10 上打开 pdf 文件
- javascript - 使用 jquery 设置复选框时遇到问题
- sql - 分配给变量的 SQL 存储过程参数
- spring-boot - 如何使用maven build在spring boot中生成fat jar期间排除资源文件夹?
- javascript - RegEx 不适用于替换 JavaScript 方法
- assembly - 6502 (Commodore 64) 中的精灵指针
- kubernetes - 添加多个外部服务时,Egress 网关无法正常工作