Skip to content

3.3 Casting and Parsing

Data จริงมาเป็น text เสมอ — CSV, form input, API response — ก่อนทำอะไรได้ คุณต้อง แปลง มันให้เป็น number ก่อน

  • Casting = บอกคอมพิวเตอร์ว่า “มองข้อมูลนี้เป็นอีก type หนึ่ง” (เช่น int → float)
  • Parsing = อ่าน text แล้วพยายามแปลงเป็น number (เช่น "123"123)

ทั้งสองอาจ ล้มเหลว ได้ — "hello" แปลงเป็น number ไม่ได้ สิ่งที่สำคัญคือ: ล้มเหลวแบบไหน?

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

Section titled “ตารางเปรียบเทียบ”
การแปลงGoogle Sheetspandas (Python)SQL
Text → NumberVALUE("123")pd.to_numeric("123")CAST('123' AS INTEGER)
Fail safelyIFERROR(VALUE("abc"), 0)pd.to_numeric(s, errors="coerce")TRY_CAST('abc' AS INTEGER)
Number → TextTO_TEXT(123) หรือ TEXT(123, "0")s.astype("string")CAST(123 AS VARCHAR)

พิมพ์ในเซลล์:

=VALUE("42") → 42 (number)
=VALUE("42.5") → 42.5
=VALUE("hello") → #VALUE! error!
=IFERROR(VALUE("hello"), 0) → 0 (fail safely)

แปลง number กลับเป็น text:

=TO_TEXT(42) → "42" (text)
=TEXT(1234.5, "#,##0.00") → "1,234.50" (formatted text)

สถานการณ์จริง: คุณ import CSV ที่มี column “price” แต่ Sheets เก็บเป็น text — ใช้ VALUE() แปลงทั้งคอลัมน์:

=ARRAYFORMULA(IFERROR(VALUE(A2:A100), ""))

เมื่อไหร่ต้อง Cast/Parse?

Section titled “เมื่อไหร่ต้อง Cast/Parse?”
สถานการณ์ทำอะไร
Import CSV ที่ทุกอย่างเป็น textParse text → number
รวมตาราง number กับ text columnCast ให้ตรงกัน
แสดงผล number ใน reportCast number → text + format
เจอ mixed data (มีทั้ง number และ “N/A”)Parse ด้วย coerce/IFERROR