decimal เป็น Value Type (Struct) ใช้สำหรับการคำนวณทางการเงินและการเงินที่ต้องการความแม่นยำสูง รองรับตัวดำเนินการ +, -, *, /, %
ตัวอย่าง: บวก Decimal
using System;
class Demo
{
static void Main()
{
decimal d1 = 5.8M;
decimal d2 = 3.2M;
d1 = d1 + d2;
Console.WriteLine(d1); // 9.0
}
}
ผลลัพธ์
9.0
ข้อดีเหนือ float/double: ไม่มีปัญหาความคลาดเคลื่อนจุดลอยตัว (Floating-point error) เช่น 0.1 + 0.2 = 0.30000000000000004 ใน double แต่ decimal จะได้ 0.3 อย่างแม่นยำ