Number.From จะพยายามแปลงค่า Input ให้เป็น Number หากเป็น Text จะพยายาม Parse ตัวเลขออกมา หากเป็น Date/Time จะแปลงเป็น Serial Number (เช่นเดียวกับ Excel)
=Number.From(value as any, optional culture as nullable text) as nullable number
=Number.From(value as any, optional culture as nullable text) as nullable number
| Argument | Type | Required | Default | Description |
|---|---|---|---|---|
| value | any | Yes | ค่าที่ต้องการแปลงเป็นตัวเลข สามารถเป็น Text, Date, Time, Logical, Duration หรือ Number เดิม | |
| culture | text | Optional | null | รหัสวัฒนธรรม (Culture Code) เช่น “en-US” หรือ “th-TH” มีผลต่อการแปลทศนิยมและหลักพัน (en-US ใช้ . คั่นทศนิยม และ , คั่นหลักพัน ส่วน de-DE ใช้สวนกลับ) |
แปลง "123.45" ให้เป็นตัวเลข 123.45 เพื่อนำไปคำนวณ
แปลงค่า Date ให้เป็นตัวเลข (เช่น 45658) เพื่อใช้ในการคำนวณทางคณิตศาสตร์
Number.From("123.45")= Number.From("123.45")
123.45
Number.From(#date(2020, 3, 20))= Number.From(#date(2020, 3, 20))
43910
Number.From("1.234,56", "de-DE")= Number.From("1.234,56", "de-DE")
1234.56
Number.From(true)= Number.From(true)
1
Number.From(#time(12, 0, 0))= Number.From(#time(12, 0, 0))
0.5
let Source = Table.FromRows({{"100"}, {"abc"}, {"50.5"}}, {"Value"}), Converted = Table.AddColumn(Source, "NumValue", each try Number.From([Value]) otherwise nu…let
Source = Table.FromRows({{"100"}, {"abc"}, {"50.5"}}, {"Value"}),
Converted = Table.AddColumn(Source, "NumValue", each try Number.From([Value]) otherwise null)
in
Converted
ตารางแสดง Value 100 และ 50.5 เป็น Number, abc เป็น null
Number.FromText ใช้ได้เฉพาะกับ Text เท่านั้น แต่ Number.From ใช้กับค่าประเภทอื่นได้ด้วย (เช่น Date, Time, Logical, Duration) ถ้าค่าเป็น Text แล้วต้องการตัวเลือกเฉพาะ Text จะใช้ Number.FromText ได้
ปกติ Number.From จะ Return Error ถ้าข้อมูลไม่สามารถแปลงได้ ดังนั้นควรใช้ try-otherwise เพื่อจัดการ Error
สำคัญมาก หากข้อมูลใช้รูปแบบ Culture ที่ต่างจาก Default (en-US) ต้องระบุ Culture หรือจะแปลงค่าผิด เช่น “1.000,50” ในเยอรมัน คือ 1000.50 แต่ถ้าไม่ระบุ Culture อาจแปลงเป็น 1.00050
Power Query ใช้ OLE Automation Date System คล้ายกับ Excel โดยนับจำนวนวันตั้งแต่ 1 มกราคม ค.ศ. 1900 สำหรับ Date และ Fractional Day สำหรับ Time
ฟังก์ชัน Number.From ใน Power Query ใช้สำหรับแปลงค่าต่างๆ ให้เป็นชนิดข้อมูลตัวเลข (Number) รองรับการแปลงจากข้อความ (Text), วันที่, เวลา หรือค่าอื่นๆ เหมือนกับการ Cast ชนิดข้อมูลในภาษาโปรแกรมมิ่ง
ที่เจ๋งของ Number.From คือมันรองรับการแปลงจากหลายประเภทข้อมูล ไม่ว่าจะเป็นข้อความ วันที่ เวลา หรือแม้แต่ Logical (true/false) ยังสามารถแปลงได้ ส่วนใหญ่ผมใช้ในการแปลง Text ตัวเลขที่มีทศนิยมหรือหลักพันที่อยู่ในรูปแบบต่างๆ เนื่องจาก Power Query บางครั้งไม่ได้อ่านข้อมูลตัวเลขออกมาเป็น Type Number โดยอัตโนมัติ
ส่วนตัวผมแนะนำให้ใช้ Number.From คู่กับ try-otherwise เพื่อหลีกเลี่ยง Error เมื่อข้อมูลไม่สามารถแปลงได้ 😎