In JavaScript, the toString() method is used to convert a number to a string representation. It allows us to specify the radix (base) of the number when converting it to a string.
Syntax:
number.toString([radix])
- number: The number to be converted to a string.
- radix (optional): An integer between 2 and 36 that represents the base of the numerical system to be used when converting the number to a string. If not specified, the default is 10.
Example:
let number = 42; let stringRepresentation = number.toString(); console.log(stringRepresentation); // Output: "42" let binaryString = number.toString(2); console.log(binaryString); // Output: "101010"
Explanation:
- In the first example, toString() is called without specifying the radix, so the number is converted to a string using the decimal base (base 10).
- In the second example, toString(2) is used, which converts the number to a binary string representation (base 2).
Use Cases:
- Display Formatting: Convert numbers to strings for displaying them in user interfaces or as part of textual output.
- Serialization: Convert numbers to strings for serializing data to be stored in files or transmitted over the network.
- Custom Number Formats: Use toString() with different radices to create custom number formats, such as binary, hexadecimal, octal, etc.
The toString() method provides flexibility in converting numbers to strings, allowing us to control the format and base of the resulting string representation.
Code Compiler Link: https://app.singhteekam.in/codecompiler/