toString(radix) Prints Other Bases

toString(radix) renders integers in bases 2 to 36 and parseInt parses them back; negative numbers keep their sign and decimals expand beyond the point.

JavascriptCli Tooling

Code

javascriptsnippet
19 lines
// toString(radix) 输出 2 到 36 任意进制的表示
const value = 255;
console.log('hex    :', value.toString(16));
console.log('octal  :', value.toString(8));
console.log('binary :', value.toString(2));
console.log('base36 :', (123456789).toString(36));

// parseInt 用同一进制解析回十进制,往返无损
console.log('back   :', parseInt(value.toString(16), 16) === value);

// 小数用 radix 也能表示
console.log('frac   :', (0.5).toString(2));

// 负数保留符号,radix 作用于绝对值
console.log('negative:', (-42).toString(16));

// 无参默认十进制;包装对象取原始值后再转
const boxed = new Number(255);
console.log('boxed  :', boxed.valueOf().toString(16) === boxed.toString(16));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

hex    : ff
octal  : 377
binary : 11111111
base36 : 21i3v9
back   : true
frac   : 0.1
negative: -2a
boxed  : true

What the code does

Top-level bindings value, boxed hold the demo state — nothing sits inside a function scope.

Applying it

The demo output is labeled (binary :, base36 :, negative:), so every printed line maps back to its originating operation.

Statements that matter

const boxed = new Number(255);
const value = 255;

Interactive Tools for This Topic

FAQ

Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `value`, `boxed`.