Kiểu decimal hỗ trợ các toán tử +, -, *, / trực tiếp. Ví dụ minh họa cộng và trừ.
Ví dụ
using System;
using System.Linq;
class Demo
{
static void Main()
{
decimal d1 = 9.5M;
decimal d2 = 4.2M;
d1 = d1 + d2;
Console.WriteLine("Cộng decimal: " + d1);
d1 = d1 - d2;
Console.WriteLine("Trừ decimal: " + d1);
}
}
Kết quả
Cộng decimal: 13.7 Trừ decimal: 9.5
Mẹo: Luôn dùng hậu tố M cho literal decimal (ví dụ: 9.5M) để tránh nhầm với double.