# C# 中将浮点数四舍五入到小数点后两位

Minahil Noor 2024年2月16日

## C# 使用 `decimal.Round()` 方法将十进制值舍入到两个十进制位

`decimal.Round()` 方法是将十进制数字四舍五入为指定的位数的最简单的方法。此方法最多允许 28 个小数位。

``````decimal.Round(decimalValueName, integerValue);
``````

``````using System;

public class RoundDecimal {
public static void Main() {
decimal decimalValue = 123.456M;
Console.WriteLine("The Decimal Value Before Applying Method: {0}", decimalValue);
Console.WriteLine();
decimalValue = decimal.Round(decimalValue, 2);
Console.WriteLine("The Decimal Value After Applying Method: {0}", decimalValue);
}
}
``````

``````The Decimal Value Before Applying Method: 123.456

The Decimal Value After Applying Method: 123.46
``````

``````using System;

public class RoundDecimal {
public static void Main() {
decimal decimalValue = 12.345M;
Console.WriteLine("The Decimal Value Before Applying Method: {0}", decimalValue);
Console.WriteLine();
decimalValue = decimal.Round(decimalValue, 2, MidpointRounding.AwayFromZero);
Console.WriteLine("The Decimal Value After Applying Method: {0}", decimalValue);
}
}
``````

``````The Decimal Value Before Applying Method: 12.345

The Decimal Value After Applying Method: 12.35
``````

`MidpointRounding.AwayFromZero` 用于将数字从零舍入。它的对应对象是 `MidpointRounding.ToEven`，它将给定的十进制数四舍五入到最接近的偶数。

``````using System;

public class RoundDecimal {
public static void Main() {
decimal decimalValue = 12.345M;
Console.WriteLine("The Decimal Value Before Applying Method: {0}", decimalValue);
Console.WriteLine();
decimalValue = decimal.Round(decimalValue, 2, MidpointRounding.ToEven);
Console.WriteLine("The Decimal Value After Applying Method: {0}", decimalValue);
}
}
``````

``````The Decimal Value Before Applying Method: 12.345

The Decimal Value After Applying Method: 12.34
``````

## C# 使用 `Math.Round()` 方法将十进制值四舍五入到两个十进制位

`Math.Round()` 方法与 `decimal.Round()` 相同。

``````Math.Round(decimalValueName, integerValue);
``````

``````using System;

public class RoundDecimal {
public static void Main() {
decimal decimalValue = 123.456M;
Console.WriteLine("The Decimal Value Before Applying Method: {0}", decimalValue);
Console.WriteLine();
decimalValue = Math.Round(decimalValue, 2);
Console.WriteLine("The Decimal Value After Applying Method: {0}", decimalValue);
}
}
``````

``````The Decimal Value Before Applying Method: 123.456

The Decimal Value After Applying Method: 123.46
``````