How to get a string representation of a number in JavaScript?

Use the toString() method to get the string representation of a number. This method converts any number to its string equivalent and supports different number bases for advanced use cases.

Syntax

number.toString()
number.toString(radix)

Parameters

radix (optional): An integer between 2 and 36 representing the base for numeric representation. Default is 10 (decimal).

Basic Example

<!DOCTYPE html>
<html>
<body>
    <script>
        var num1 = 25;
        
        document.write(num1.toString() + "<br>");
        document.write((30.2).toString() + "<br>");
        document.write((-40).toString() + "<br>");
        document.write((15.5).toString());
    </script>
</body>
</html>
25
30.2
-40
15.5

Using Different Bases

<!DOCTYPE html>
<html>
<body>
    <script>
        var num = 15;
        
        document.write("Decimal: " + num.toString() + "<br>");
        document.write("Binary: " + num.toString(2) + "<br>");
        document.write("Octal: " + num.toString(8) + "<br>");
        document.write("Hexadecimal: " + num.toString(16));
    </script>
</body>
</html>
Decimal: 15
Binary: 1111
Octal: 17
Hexadecimal: f

Alternative Methods

<!DOCTYPE html>
<html>
<body>
    <script>
        var num = 42;
        
        // Using toString()
        document.write("toString(): " + num.toString() + "<br>");
        
        // Using String() constructor
        document.write("String(): " + String(num) + "<br>");
        
        // Using template literal
        document.write("Template literal: " + `${num}` + "<br>");
        
        // Using concatenation
        document.write("Concatenation: " + (num + ""));
    </script>
</body>
</html>
toString(): 42
String(): 42
Template literal: 42
Concatenation: 42

Comparison

Method Supports Base Handles null/undefined Performance
toString() Yes No - throws error Fast
String() No Yes Fast
Template literal No Yes Moderate
Concatenation No Yes Slowest

Conclusion

Use toString() for converting numbers to strings, especially when you need different number bases. For safer conversion that handles null values, use String() constructor instead.

Updated on: 2026-03-15T23:18:59+05:30

538 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements