Javascript Reference - JavaScript Number toString() Method








The toString() method converts a number to a string.

toString() method optionally accepts a single argument indicating the radix:

  • string toString()
    Represents a number in base 10
  • string toString(2)
    Represents a number in base 2(binary)
  • string toString(8)
    Represents a number in base 8(octal)
  • string toString(16)
    Represents a number in base 16(hexadecimal)

var num = 10; 

console.log(num.toString()); //"10" 
console.log(num.toString(2)); //"1010" 
console.log(num.toString(8)); //"12" 
console.log(num.toString(10)); //"10" 
console.log(num.toString(16)); //"a" 

The code above generates the following result.





Browser Support

toString Yes Yes Yes Yes Yes

Syntax

number.toString(radix)

Parameter Values

Parameter Description
radix Optional. What base to use for representing a numeric value. Must be an integer between 2 and 36.
  • 2 - The number will show as a binary value
  • 8 - The number will show as an octal value
  • 16 - The number will show as an hexadecimal value

Return Value

A String type value representing a number.





Example

The following code shows how to Convert a number to a string.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {<!--from w w w  . j  a va2s .  c o  m-->
    var num = 15;
    var n = num.toString();
    document.getElementById("demo").innerHTML = n;
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 2

The following code shows how to convert a number to a string, using different bases.


<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">test</button>
<!--  w ww .ja  v  a2 s .  c om-->
<p id="demo"></p>

<script>
function myFunction() {
    var num = 15;
    var a = num.toString();
    var b = num.toString(2);
    var c = num.toString(8);
    var d = num.toString(16);

    var n = a + "<br>" + b + "<br>" + c + "<br>" + d;

    document.getElementById("demo").innerHTML=n;
}
</script>
</body>
</html>

The code above is rendered as follows: