Number Formats & Precision
ทำไม Format สำคัญ
Section titled “ทำไม Format สำคัญ”ตัวเลขตัวเดียวกันแสดงผลได้หลายแบบ — เงิน, เปอร์เซ็นต์, วิทยาศาสตร์ — แต่ค่าข้างในเหมือนกัน การเลือก Format ที่ถูกต้องช่วยให้อ่านข้อมูลง่ายขึ้นและลดข้อผิดพลาด
การจัดรูปแบบตัวเลขพื้นฐาน
Section titled “การจัดรูปแบบตัวเลขพื้นฐาน”| Format | ตัวอย่าง | วิธีใช้ |
|---|---|---|
| Currency | ฿1,234.56 | Format > Number > Currency |
| Percentage | 75.50% | Format > Number > Percent |
| Scientific | 1.23E+06 | Format > Number > Scientific |
| Custom | #,##0.00 | Format > Number > Custom |
ใช้ TEXT() สำหรับ Custom Format
Section titled “ใช้ TEXT() สำหรับ Custom Format”=TEXT(1234.5, "#,##0.00") → "1,234.50"=TEXT(0.75, "0.0%") → "75.0%"=TEXT(1234.5, "$#,##0.00") → "$1,234.50"=TEXT(42, "000000") → "000042"#include <stdio.h>int main() { double val = 1234.5; printf("Currency: $%.2f\n", val); printf("Scientific: %e\n", val); printf("Padded: %010.2f\n", val); return 0;}val = 1234.5print(f"Currency: ${val:,.2f}") # $1,234.50print(f"Percentage: {0.75:.1%}") # 75.0%print(f"Scientific: {val:.2e}") # 1.23e+03print(f"Padded: {42:06d}") # 000042SELECT FORMAT(1234.5, 2) AS currency, -- 1,234.50 CONCAT(75.5, '%') AS percentage, -- 75.5% FORMAT(1234.5, 'E2') AS scientific; -- varies by DBปัญหา Floating Point: 0.1 + 0.2
Section titled “ปัญหา Floating Point: 0.1 + 0.2”ลองพิมพ์ใน Cell:
=0.1+0.2ดูเหมือนจะได้ 0.3 — แต่ลองใช้:
=TEXT(0.1+0.2, "0.00000000000000000")ผลลัพธ์: 0.30000000000000004
วิธีรับมือ
Section titled “วิธีรับมือ”=ROUND(0.1+0.2, 10) → 0.3 (ตัดทศนิยมส่วนเกิน)=ROUND(A1*100)/100 → ปัดเศษเพื่อเปรียบเทียบ#include <stdio.h>int main() { printf("%.17f\n", 0.1 + 0.2); // 0.30000000000000004 return 0;}print(f"{0.1 + 0.2:.17f}") # 0.30000000000000004from decimal import Decimalprint(Decimal('0.1') + Decimal('0.2')) # 0.3 (exact)-- ใช้ DECIMAL type แทน FLOAT เพื่อความแม่นยำSELECT CAST(0.1 AS DECIMAL(10,2)) + CAST(0.2 AS DECIMAL(10,2));-- ผลลัพธ์: 0.30- Format เปลี่ยนแค่การแสดงผล ไม่เปลี่ยนค่าจริงในเซลล์
- TEXT() ใช้แปลงตัวเลขเป็นข้อความในรูปแบบที่ต้องการ
- Floating Point เป็นปัญหาของทุกภาษา — ใช้ ROUND() เมื่อต้องการเปรียบเทียบ