หลายๆคนคงเคยเจอปัญหา กับ การรับค่าจาก input เป็นตัวเลขมา เพื่อจะนำมาคำนวนกัน เช่น รับ “1” และ “2” มาและอยากจะนำมาบวกกัน แต่ทำไมผลลัพท์มันจึง ออกมาเป็น “12” หวา แต่ถ้าบางคนยังมองไม่เห้น ภาพ หรือ งงๆ อยู่ลองดูตัวอย่าง ต่อไปนี้แล้วกันนะ ครับ (อธิบายด้วย code ละ )
คำถาม คือ
Step (1) จะต่อ (string) “1”, “2”, “3” ให้เป็น “123” ได้อย่างไร
Step (2) จะเปลี่ยน (string) “123” ให้เป็น (int)123 ได้อย่างไร
Step (3) 123 + 100 = 223
Step (4) จะเปลี่ยน (int) 223 เป็น (string) “223” ได้อย่างไร
keyword ของการแก้ปัญหานี้ คือ method parseInt () และ toString () และ ถ้าหากคุณอยากรู้ว่า ตัวแปรนั้นมี type เป็นชนิดไหน ลองใช้ typeof ดูนะครับ
<script type="text/javascript"> /** * print out the value and the type of the variable passed in */ function printWithType(val) { document.write('<pre>'); document.write(val); document.write(' '); document.writeln(typeof val); document.write('</pre>'); } //กำหนดค่าตัวแปรกันก่อน var a = "1", b = "2", c = "3", result; // Step (1) จะต่อ (string) "1", "2", "3" ให้เป็น "123" ได้อย่างไร // - ใช้ "+" ในการ ต่า String result = a + b + c; printWithType(result); //123 (string) // หรือ ถ้าไม่แน่ใจว่าค่าที่รับมาเป็น string ก็ เปลี่ยนให้เป็น String // โดย method toString แล้ว ก็ "+" เหมือนเดิม result = a.toString() + b.toString() + c.toString(); printWithType(result); // 123 (string) // Step (2) จะเปลี่ยน (string) "123" ให้เป็น (int)123 ได้อย่างไร // ให้ใช้ method parseInt เพื่อนที่จะเปลี่ยน String เป็น int result = parseInt(result,10); printWithType(result); // 123 number // Step (3) 123 + 100 = 223 // เนื่องจากค่าที่ได้ เป็น int อยู่แล้ว ก้ สามารถ + กันได้เลย result = result + 100; printWithType(result); // 223 number // Step (4) จะเปลี่ยน (int) 223 เป็น (string) "223" ได้อย่างไร // แน่นอนว่าจะต้องเป็น พระเอกของเรา method toString ในการเปลี่ยน int เป็น String result = result.toString(); printWithType(result); // 223 string // ก่อนจบบทความนี้ของฝากนิดนึง ว่าถ้าเกิด (int)result บวกกับ (String)"" ซึ่งเป็นค่าวางๆ // ผลลัพท์ที่ได้จะเป็น type String นะครับ result = result + ""; printWithType(result); //223 string </script>
อ้างอิง : http://www.w3schools.com ,http://stackoverflow.com/questions/971039/javascript-string-and-number-conversion
http://www.phpparty.com/index.php/%E0%B9%80%E0%B8%97%E0%B8%84%E0%B8%99%E0%B8%B4%E0%B8%84%E0%B8%81%E0%B8%B2%E0%B8%A3%E0%B9%80%E0%B8%82%E0%B8%B5%E0%B8%A2%E0%B8%99%E0%B9%82%E0%B8%9B%E0%B8%A3%E0%B9%81%E0%B8%81%E0%B8%A3%E0%B8%A1-php/551-%E0%B8%82%E0%B9%89%E0%B8%AD%E0%B9%81%E0%B8%95%E0%B8%81%E0%B8%95%E0%B9%88%E0%B8%B2%E0%B8%87%E0%B8%A3%E0%B8%B0%E0%B8%AB%E0%B8%A7%E0%B9%88%E0%B8%B2%E0%B8%87-exec,-shell_exec,-system-%E0%B9%81%E0%B8%A5%E0%B8%B0-passthru()-%E0%B8%82%E0%B8%AD%E0%B8%87-PHP