# 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
``````