Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

แปลงตัวเลขเป็น Base อื่นๆ ด้วย toString() ใน JavaScript

toString() ไม่ได้ใช้แค่แปลง array เป็น string แต่อย่างน้อยแปลงตัวเลขเป็น base อื่นๆ ได้ (base 2 ถึง base 36)

ตัวอย่างที่ 1

ตัวเลข 26 แปลงเป็น base ต่างๆ 2 ถึง 36

<html> <body> <script> 
    var Num = 26; 
    document.write("The number 26 can be converted into" + "<br>" + 
        "Binary - " + Num.toString(2) + "<br>" + 
        "Octal - " + Num.toString(8) + "<br>" + 
        "Decimal - " + Num.toString(10) + "<br>" + 
        "Hexadecimal - " + Num.toString(16)); 
</script> </body> </html>

ผลลัพธ์

The number 26 can be converted into Binary - 11010 Octal - 32 Decimal - 26 Hexadecimal - 1a

ตัวอย่างที่ 2

ตัวเลข 36 แปลงเป็น binary, octal, decimal, hexadecimal

<html> <body> <script> 
    var Num = 36; 
    document.write("The number 36 can be converted into" + "<br>" + 
        "Binary - " + Num.toString(2) + "<br>" + 
        "Octal - " + Num.toString(8) + "<br>" + 
        "Decimal - " + Num.toString(10) + "<br>" + 
        "Hexadecimal - " + Num.toString(16)); 
</script> </body> </html>

ผลลัพธ์

The number 36 can be converted into Binary - 100100 Octal - 44 Decimal - 36 Hexadecimal - 24