decimal Module
decimal module ให้ความแม่นยำสูงในการคำนวณทศนิยม เหมาะสำหรับงานการเงิน ที่ต้องการความถูกต้องทุกสตางค์ ไม่เหมือน float ที่มีปัญหา binary representation
ทำไมต้องใช้ Decimal
Section titled “ทำไมต้องใช้ Decimal”ในงานการเงิน ความผิดพลาดเพียง 0.01 บาท เมื่อสะสมหลายล้านรายการ อาจกลายเป็นเงินจำนวนมาก นี่คือเหตุผลที่เราต้องใช้ Decimal:
- ความแม่นยำ 100% - ไม่มี rounding errors จาก binary representation
- Control การปัดเศษ - เลือก rounding mode ได้ตามต้องการ
- ปรับ Precision ได้ - กำหนดความละเอียดได้
- มาตรฐานการเงิน - รองรับ IEEE 854
ปัญหาของ float
Section titled “ปัญหาของ float”# ปัญหา: float ใช้ binary representation# ทศนิยมบางตัวไม่สามารถแทนได้แม่นยำใน binary
print("=== ปัญหาพื้นฐานของ float ===\n")
# ปัญหา 1: 0.1 + 0.2 ไม่เท่ากับ 0.3result = 0.1 + 0.2print(f"0.1 + 0.2 = {result}") # 0.30000000000000004print(f"0.1 + 0.2 == 0.3? {result == 0.3}") # False!
# ปัญหา 2: ดู representation จริงprint(f"\nActual representation:")print(f" 0.1 = {repr(0.1)}")print(f" 0.2 = {repr(0.2)}")print(f" 0.1+0.2 = {repr(0.1 + 0.2)}")
# ปัญหา 3: การคำนวณราคาprice = 19.99quantity = 3total = price * quantityprint(f"\n19.99 * 3 = {total}") # ดูถูกprint(f"Exact value: {repr(total)}") # แต่จริงๆ คือ 59.97000000000001
# ปัญหา 4: Error สะสมtotal = 0.0for _ in range(1000): total += 0.001print(f"\n0.001 * 1000 = {total}") # 0.9999999999999062 (ควรเป็น 1.0)
# ปัญหา 5: การเปรียบเทียบa = 1.1 + 2.2b = 3.3print(f"\n1.1 + 2.2 = {a}")print(f"3.3 = {b}")print(f"1.1 + 2.2 == 3.3? {a == b}") # False!เข้าสู่ระบบเพื่อดูเนื้อหาเต็ม
ยืนยันตัวตนด้วยบัญชี Google เพื่อปลดล็อกบทความทั้งหมด
Login with Google