ทั้งสามเป็น **Value Types** (มาจาก System.ValueType) แต่ต่างกันใน Precision, Range และ Use Case
ตารางเปรียบเทียบ
| คุณสมบัติ | float | double | decimal |
|---|---|---|---|
| ขนาด | 32-bit (4 bytes) | 64-bit (8 bytes) | 128-bit (16 bytes) |
| Precision | ~7 digits | ~15-16 digits | 28-29 digits |
| Range | ±1.5×10⁻⁴⁵ ~ ±3.4×10³⁸ | ±5.0×10⁻³²⁴ ~ ±1.7×10³⁰⁸ | ±1.0×10⁻²⁸ ~ ±7.9×10²⁸ |
| Default Value | 0.0f | 0.0d | 0.0m |
| Suffix | F/f | D/d (optional) | M/m |
| Type | System.Single | System.Double | System.Decimal |
| IEEE 754 | Single Precision | Double Precision | ไม่ใช่ (Base-10) |
ตัวอย่าง宣告
float f = 3.5f; // ต้องมี f double d = 5.78788; // Default สำหรับ Real Literals decimal m = 1.0m; // ต้องมี m
เมื่อไหร่ควรใช้อะไร
- float: 3D Graphics, Game Dev, Scientific Computing ที่ต้องการ Speed/Memory > Precision
- double: **General Purpose** - Default Choice สำหรับ Real Numbers
- decimal: **Financial/Monetary Calculations** - ต้องการความแม่นยำ Base-10 (ไม่มี Floating Point Errors)
ตัวอย่าง Decimal Precision
double d = 0.1 + 0.2; Console.WriteLine(d); // 0.30000000000000004 ❌ decimal m = 0.1m + 0.2m; Console.WriteLine(m); // 0.3 ✅
Performance Note
decimal ช้ากว่า double ประมาณ 10-20 เท่า (Software Implementation vs Hardware FPU)