toString()方法不仅用于将数组转换为字符串,还用于将数字转换为其他基本形式。toString()方法可以从2到36的数字输出数字。
我们来看一个例子
在以下示例中,数字46转换为2到36的各种基本形式。
<html> <body> <script> var Num = 26; document.write( "The number 26 can be converted in to" + "</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 in to Binary - 11010 octal - 32 Decimal - 26 hexadecimal - 1a
在以下示例中,使用toString()方法将数字36转换为二进制,八进制,十进制和十六进制基本形式。
<html> <body> <script> var Num = 36; document.write( "The number 36 can be converted in to" + "</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 in to Binary - 100100 octal - 44 Decimal - 36 hexadecimal -24