The toString()
method converts a number to a string.
toString() method optionally accepts a single argument indicating the radix:
string toString()
string toString(2)
string toString(8)
string toString(16)
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.
toString |
Yes | Yes | Yes | Yes | Yes |
number.toString(radix)
Parameter | Description |
---|---|
radix | Optional. What base to use for representing a numeric value.
Must be an integer between 2 and 36.
|
A String type value representing a number.
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:
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: