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

Data Type ไหนเหมาะสำหรับ Currency ใน C#

คำตอบคือ decimal (128-bit) เหมาะสำหรับการคำนวณทางการเงิน/การเงิน

  • Range: 1.0 × 10⁻²⁸ ถึง ~7.9 × 10²⁸
  • Precision: 28-29 Significant Digits
  • Suffix: m หรือ M (เช่น 2.1m)

ตัวอย่าง Min/Max Value

Console.WriteLine($"Decimal Min: {decimal.MinValue}");
Console.WriteLine($"Decimal Max: {decimal.MaxValue}");
Decimal Min: -79228162514264337593543950335
Decimal Max: 79228162514264337593543950335

ทำไมไม่ใช้ float/double?

float/double เป็น Binary Floating Point ไม่สามารถแทนค่าทศนิยมบางค่าได้แม่นยำ (เช่น 0.1) → เกิด Round-off Errors

decimal เป็น Base-10 Floating Point แทนค่า 0.1 ได้แม่นยำ เหมาะกับเงินตรา

ตัวอย่างแปลงสกุลเงิน

decimal usd = 2.5m;
decimal inrPerUsd = 75.04m;
decimal inr = usd * inrPerUsd; // 187.600
USD: 2.5
INR value of one USD: 75.04
INR value: 187.600