用C#保留2位小数
时间: 2023-06-30 07:26:37 浏览: 59
在C#中,可以使用以下方式保留2位小数:
1. 使用ToString()方法:
```
double num = 3.14159265359;
string result = num.ToString("0.00");
Console.WriteLine(result); // 输出 3.14
```
2. 使用String.Format()方法:
```
double num = 3.14159265359;
string result = String.Format("{0:0.00}", num);
Console.WriteLine(result); // 输出 3.14
```
3. 使用Math.Round()方法:
```
double num = 3.14159265359;
double result = Math.Round(num, 2);
Console.WriteLine(result); // 输出 3.14
```
以上三种方式都可以将一个double类型的数保留两位小数。
相关问题
c#保留2位小数输出
在 C# 中,你可以使用以下方法来保留一个数值的小数位数为两位并进行输出:
```csharp
double number = 3.14159;
Console.WriteLine(number.ToString("0.00"));
```
这将输出:3.14
另外,你也可以使用字符串插值:
```csharp
double number = 3.14159;
Console.WriteLine($"{number:0.00}");
```
同样,这也会输出:3.14
C# decimal 保留2位小数
在 C# 中,可以使用 `Math.Round` 方法来保留指定位数的小数。下面是一个示例代码:
```csharp
decimal number = 3.14159m;
decimal roundedNumber = Math.Round(number, 2);
Console.WriteLine(roundedNumber);
```
这段代码将会输出 `3.14`,即保留了两位小数。注意,使用 `Math.Round` 方法会进行四舍五入。如果需要进行其他舍入操作,可以使用 `Math.Floor` 或 `Math.Ceiling` 方法。