Devdit
 

แปลง String เป็น Int JavaScript

3.9K

สอนเขียนโค้ดแปลง String เป็น Int ด้วยภาษา JavaScript โดยใช้คำสั่ง parseInt โดยคำสั่งนี้จะแปลงข้อมูลที่ต้องการให้เป็นชนิดตัวเลข (Interger) และคืนค่ากลับมาเป็นตัวเลข สามารถเขียนโปรแกรมได้ดังนี้

 

ตัวอย่าง แปลง String เป็น Int JavaScript

<script>
    var number1 = "100";
    var number2 = "99";
    var total = parseInt( number1 ) + parseInt( number2 );
    console.log( "ใช้คำสั่ง parseInt ตัวแปร total = "+total );
    
    total = number1 + number2;
    console.log( "ไม่ใช้คำสั่ง parseInt ตัวแปร total = "+total );
</script>

ผลลัพธ์

ใช้คำสั่ง parseInt ตัวแปร total = 199
ไม่ใช้คำสั่ง parseInt ตัวแปร total = 10099
เขียน 2 ปีที่แล้ว
ชอบ
ลิ้งก์
แชร์
Devdit มีช่อง YouTube แล้ว
เราสร้างวิดีโอเกี่ยวกับเทคโนโลยี ทำตามง่ายๆ