JavaScript num.toString([radix]) method


The num.toString([radix]) method in JavaScript is used to convert a number into a string representation in a specified base (radix). This method is particularly useful for representing numbers in different numeral systems, such as binary, octal, decimal, and hexadecimal.

Syntax:

num.toString([radix])
  • num: The number you want to convert to a string.
  • radix (optional): An integer between 2 and 36 that represents the base in which the number should be expressed. If omitted, it defaults to 10 (decimal).

Return Value:

  • Returns a string representing the number in the specified base.

Valid Radix Values:

  • 2: Binary
  • 8: Octal
  • 10: Decimal (default)
  • 16: Hexadecimal
  • 36: Base-36 (uses digits 0-9 and letters A-Z)

Example Usage:

  1. Basic Usage with Default Radix:

    let num1 = 255; console.log(num1.toString()); // "255" (default is base 10)
  2. Binary Representation:

    let num2 = 5; console.log(num2.toString(2)); // "101" (binary representation)
  3. Octal Representation:

    let num3 = 64; console.log(num3.toString(8)); // "100" (octal representation)
  4. Hexadecimal Representation:

    let num4 = 255; console.log(num4.toString(16)); // "ff" (hexadecimal representation)
  5. Base-36 Representation:

    let num5 = 123456; console.log(num5.toString(36)); // "zq" (base-36 representation)
  6. Invalid Radix:

    • If the radix is less than 2 or greater than 36, a RangeError will be thrown:
    console.log(num1.toString(1)); // RangeError: radix must be between 2 and 36 console.log(num1.toString(37)); // RangeError: radix must be between 2 and 36

Summary:

The num.toString([radix]) method in JavaScript is a powerful way to convert numbers into string representations in various bases. It supports a wide range of numeral systems, making it useful for applications involving different number formats, such as binary and hexadecimal. The method provides flexibility in representing numerical data in a format that best suits the application's needs.