Javascript toString() Method

      No Comments on Javascript toString() Method




JavaScript String toString() Method:

Javascript String toString() method returns the content of the String.
e.g.

var str = “HelloWorld”;
console.log(str.toString());

This will print HelloWorld on the console.

JavaScript Date toString() Method:

JavaScript Date toString() Method will give the current date of the system.

e.g.
var date = new Date();
var currdt = date.toString();
console.log(“Current date and time =”+currdt);

This will print the current date and time in the console.

JavaScript Number toString() method:

There are two variant of toString() in javascript.

(1) toString()
(2) toString(var radix)

(1) toString() : It simply converts a number into a string.

var number = 167;
var str = number.toString();
console.log("Type of str = "+typeof(str) + " , str Value = "+str);

So, the above program will print the following in the console.
Type of str = string , str Value = 167

(2) toString(var radix) : It converts the number to string according to the radix passed as an argument.

Let’s take an example for this.

<!DOCTYPE html>
<html>
<body>
<button onclick="convert()">Click to Convert to Different Radix</button>
<p id="output"></p>
<script>
function convert() {
   var number = 14;
   var numberToRadix2 = number.toString(2)
   var str = "Type of numberToRadix2 =" + typeof(numberToRadix2) + ", output = "+ numberToRadix2;
   document.getElementById("output").innerHTML=str;
}
</script>
</body>
</html>

Output of the above code when clicked on the buttion is as below:
Type of numberToRadix2 =string, output = 1110

Similarly, radix can be changed to different values. It can be passed as 4,8,10,12,14,16 etc.

Leave a Reply