在C#中,可以使用Math.Round()
函數對貨幣計算進行四舍五入。以下是一個簡單的示例:
using System;
class CurrencyCalculation
{
static void Main()
{
// 假設我們有兩個貨幣值
decimal amount1 = 1234.567m;
decimal amount2 = 789.012m;
// 對貨幣值進行四舍五入到小數點后兩位
decimal roundedAmount1 = Math.Round(amount1, 2);
decimal roundedAmount2 = Math.Round(amount2, 2);
// 計算兩個四舍五入后的貨幣值的和
decimal total = roundedAmount1 + roundedAmount2;
// 輸出結果
Console.WriteLine("四舍五入后的金額1: {0}", roundedAmount1);
Console.WriteLine("四舍五入后的金額2: {0}", roundedAmount2);
Console.WriteLine("兩個四舍五入后的金額之和: {0}", total);
}
}
在這個示例中,我們首先定義了兩個貨幣值amount1
和amount2
。然后,我們使用Math.Round()
函數將這些值四舍五入到小數點后兩位。最后,我們將四舍五入后的金額相加,并輸出結果。
注意:在C#中,貨幣值通常使用decimal
類型表示,因為它提供了固定的小數位數,可以避免浮點數計算中的精度問題。