There are multiple ways to convert a string to a number, but I am going to demonstrate 3 common ways here. The first one is by using the Number constructor. The second one is by using the plus(+) operator and the third one is by using the parseFloat() method. You can also go with the parseInt() method but this method will fail if your string contains decimal numbers since it will return a whole number.
In the following example, we will enter a random number in the input field. By default, whatever you enter in the input field is of string type. We will convert it into a number and display it on the screen upon button click. Please have a look over the code example and the steps given below.
HTML & CSS
We have a few elements in the HTML file and that includes div, button, input, and h1. The div element with a class of container is just a wrapper for the rest of the elements.
The inner text for the button element is “Get” and for the h1 element, it is “Output”.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.