JavaScript Number Base Conversion

JavaScript can convert Number values to bases from 2 through 36 with toString(radix), and parse text written in another base with parseInt(text, radix).

const decimal = 255;
console.log(decimal.toString(16)); // "ff"
console.log(parseInt("ff", 16)); // 255

Common number bases Top ↑

Decimal uses base 10, binary uses base 2, octal uses base 8, and hexadecimal uses base 16. Hexadecimal digits after 9 are represented by a through f. Web colors often use hexadecimal notation such as #0000ff.

Decimal, hexadecimal, octal and binary examples Top ↑

DecimalHexOctalBinary
0000
1111
22210
33311
444100
555101
666110
777111
88101000
99111001
10a121010
11b131011
12c141100
13d151101
14e161110
15f171111
16102010000

Convert decimal to binary, octal or hexadecimal Top ↑

const n = 255;
console.log(n.toString(2));  // "11111111"
console.log(n.toString(8));  // "377"
console.log(n.toString(16)); // "ff"

Convert binary, octal or hexadecimal text to decimal Top ↑

console.log(parseInt("11111111", 2)); // 255
console.log(parseInt("377", 8));      // 255
console.log(parseInt("ff", 16));      // 255

See parseInt() for detailed radix rules.

JavaScript supports radixes from 2 through 36 Top ↑

console.log((35).toString(36)); // "z"

A radix outside 2–36 causes Number.prototype.toString() to throw a RangeError.

Negative values keep their sign Top ↑

console.log((-15).toString(2)); // "-1111"

This is a signed textual representation, not a two's-complement bit pattern.

Invalid digits and NaN Top ↑

const value = parseInt("102", 2);
console.log(value); // 2 because parsing stops before the invalid digit 2

If you require the entire input to be valid for a base, validate the string before parsing instead of relying only on parseInt().

Large integer precision Top ↑

These conversions return ordinary JavaScript Numbers, so values beyond the safe-integer range can lose integer precision. Use BigInt when an exact very large integer is required and the surrounding application supports it.

Decimal and hexadecimal conversion Top ↑

Continue with the dedicated decimal to hexadecimal and hexadecimal to decimal tutorial.

JavaScript Math Reference




Subscribe to our YouTube Channel here



plus2net.com










✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer