Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

Number.prototype.toString(radix): format a number in a chosen base

Convert a `Number` to text in a base from 2 to 36. Learn how JavaScript selects and coerces the base, and why formatting a number is not the same as parsing text.

Version: ECMAScript 2024 and the current web platform; runtime support varies

Syntax

number.toString()
number.toString(radix)

Number.prototype.toString(radix) returns a string without changing the number. radix is the numeral base: 2 gives binary and 16 gives hexadecimal. Omitting it or passing undefined selects base 10. The this value must be a Number primitive or a Number object; any other value, such as a string, causes a TypeError.

In ECMAScript 2024, a supplied radix is coerced to a Number and any finite fractional value is truncated toward zero, so "16.9" selects base 16. A resulting base outside 2 through 36 inclusive causes a RangeError; this includes null and NaN (which become zero), as well as infinities. A Symbol or BigInt radix causes a TypeError during coercion.

The result uses digits 0–9 followed by lowercase a–z, with no added 0b or 0x prefix. A leading - is a sign, not a two’s-complement encoding, and . separates the fractional part. Both +0 and -0 produce "0"; special values produce "NaN", "Infinity", and "-Infinity". Base 10 can use scientific notation, such as "1e+21".

Changing the base cannot recover precision already lost in the Number value. The last significant digit is not always uniquely specified, so do not assume identical strings across engines. For large integers that must stay exact, use BigInt from the start and call BigInt.prototype.toString. parseInt(text, radix) reads an integer prefix, but it neither validates the whole string nor recovers fractions: parseInt("ff!", 16) returns 255.

Examples

{
  const n = 255;
  console.log(n.toString());
  console.log(n.toString(2));
  console.log(n.toString(16));
  console.log(n.toString("16.9"));
  console.log((-10.5).toString(2));
  console.log(parseInt(n.toString(16), 16));

  try {
    n.toString(37);
  } catch (error) {
    console.log(error.name);
  }
}

Result

255
11111111
ff
ff
-1010.1
255
RangeError

The same number is printed in decimal, binary, and hexadecimal. The argument `"16.9"` selects base `16`, the negative fraction keeps its sign, and base `37` causes a `RangeError`.

Related lessons

  • JavaScript · Lesson 2 · Advanced · Version: 4
  • JavaScript · Lesson 3 · Advanced · Version: 4

Sources