Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ความแตกต่างระหว่าง Float, Double และ Decimal ใน C#

ทั้งสามเป็น **Value Types** (มาจาก System.ValueType) แต่ต่างกันใน Precision, Range และ Use Case

ตารางเปรียบเทียบ

คุณสมบัติfloatdoubledecimal
ขนาด32-bit (4 bytes)64-bit (8 bytes)128-bit (16 bytes)
Precision~7 digits~15-16 digits28-29 digits
Range±1.5×10⁻⁴⁵ ~ ±3.4×10³⁸±5.0×10⁻³²⁴ ~ ±1.7×10³⁰⁸±1.0×10⁻²⁸ ~ ±7.9×10²⁸
Default Value0.0f0.0d0.0m
SuffixF/fD/d (optional)M/m
TypeSystem.SingleSystem.DoubleSystem.Decimal
IEEE 754Single PrecisionDouble 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)