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
: The number you want to convert to a string.radix
(optional): An integer between2
and36
that represents the base in which the number should be expressed. If omitted, it defaults to10
(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:
Basic Usage with Default Radix:
Binary Representation:
Octal Representation:
Hexadecimal Representation:
Base-36 Representation:
Invalid Radix:
- If the
radix
is less than2
or greater than36
, aRangeError
will be thrown:
- If the
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.