JavaScript: Prompts and turning Strings in Numbers using parseInt() and parseFloat()


Learning objectives:

       Getting values into the program using prompt().

       Turning strings into numbers using parseInt() and parseFloat().

       The alert() function.

       The % (modulo) operator.



So far we have learned about variables, set them using = to strings and numbers, and displayed the result on the screen using document.write(). However, a program is fairly useless if we have to set all the data in advance, and we need some way of getting the data into the program.




There is a special instruction called prompt() which displays a box on the screen and asks the user for a value. This is then set into a variable. Here is how you use the instruction:


friend_name = prompt("Please enter your friend's name", "Diane");


What you see is the following:



The prompt box carries a message - in this case, it's Please enter your friend's name and a default value, which is Diane. The idea is that the user types the friend's name instead of this default value, and then click on OK. If the user didn't type anything, but just clicked on the OK button, then the value stored in the variable would be "Diane". The two items are passed to the prompt() instruction inside the brackets, just as strings to be displayed on the screen are passed to document.write() inside the brackets. We call these parameters.


The prompt() instruction takes two parameters: firstly, the message asking for the input, and then the default value. There is a comma between the two parameters. Compare the picture of the box above with the instruction. The space after the comma is optional - I put it in because it tends to make the instruction more readable.


Whatever the user types - even if the box is cleared with the delete key and nothing is typed - then that value is stored in the variable. In this case the variable altered is friend_name. If the user typed "Bill Clinton" in the box, then the instruction would be equivalent to the instruction


friend_name = "Bill Clinton";


If the user cleared the box (i.e. deleted the default value using the Del key) and then clicked on OK, then the instruction is equivalent to typing:


friend_name = "";


(i.e. an empty string). What is the value to which the variable is set if the user clicks on Cancel? That I will leave you to find out for yourself!


If you don't want to specify a default value (i.e. you want the slot to be blank when the box appears) then just specify the default value as a blank string, as follows:


var proverb = prompt("Type a saying", "");



In this case, there is no default value. Similarly, you could leave the prompt message blank as well, although the user would probably not know what he or she was required to enter!


Converting strings to numbers


The problem with the prompt() instruction is it always returns a string. If we used it to get two numbers from the user and add them, we are going to run into problems:



var first_number = prompt("Enter the first number", "");

var second_number = prompt("Enter the second number", "");

var answer = first_number + second_number;

document.write("The answer is " + answer);



If you enter 3 for the first number and 5.6 for the second, you should get the answer 8.6, but in fact you get the answer 35.6. What's gone wrong?


Well, the variables first_number and second_number are set to the string values "3" and "5.6" which, although they look like numbers are actually string. The + sign then concatenates them to form a longer string.


What we want is a way to convert the string that prompt() gives us into a number. There are two instructions that we can use, parseInt() and parseFloat().


The instruction parseInt() will take a string, either as a constant inside quotation marks or a variable, or even as an expression, and will turn it into a whole number. The 'whole' is important in that - the "Int" part of the instruction stands for "integer", which is the technical name for a whole number.


For instance, the following instruction stores the number 7 in the variable x:


x = parseInt("7");


Similarly, the following instruction adds the number 4.55 to the number 10 and displays the result (14.55) on the screen:


var digit0 = "0";

document.write(4.55 + parseInt("1" + digit0) + "<P>");


The first thing that happens in that instruction is that the two strings "1" and "0" (stored in the variable digit0) are concatenated into the string "10". The instruction parseInt() then turns this into the number 10, which is then added to the number 4.55. The number is then concatenated with the "<P>" tag (giving a paragraph break) and the whole lot is displayed on the screen.


"Ah!" I hear you say, "I thought that concatenating numbers with strings would turn the numbers into strings themselves. You should get 4.5510 on the string, shouldn't you?" No. The command we have above is equivalent to


document.write(4.55 + 10 + "<P>");


In this case, the first + sign that the instruction comes across is the numeric addition - it adds the numbers together. It is only after this that it encounters + with a string following it. At this point, it takes the answer to the addition and concatenates it with the string containing <P>.


So what is parseFloat() then? Well, this is the instruction you would use if you thought that the answer might be a decimal (non whole number) answer. For instance, if you asked the user for the length of a building or the weight of an elephant, then these could well be decimals:


var elephant, building;

var string1, string2;

string1 = prompt("Enter the length of the building in yards", "");

building = parseFloat(string1);

string2 = prompt("Enter the weight of the elephant in tons", "");

elephant = parseFloat(string2);


Of course, if parseFloat() is handed a whole number, it can still cope with it. It doesn't have to produce a decimal number. Indeed decimals can be whole numbers themselves (i.e. there is nothing special about 7, as it is the same as 7.0). The following instruction is perfectly correct:


var x = "500";

var y = parseFloat(x);

document.write(y + 100);


It will set the variable y to the number 500. This is proved by the document.write() instruction which correctly adds the variable to 100 and displays the number 600.


The word 'Float' stands for "floating point number" which is the technical name for a decimal number. That example has also shown how we can solve our problem with the addition program you saw above. Change the program to the following, and it should work properly:



var first_number = parseFloat(prompt("Enter the first number", ""));

var second_number = parseFloat(prompt("Enter the second number", ""));

var answer = first_number + second_number;

document.write("The answer is " + answer);



Here we have included one instruction inside another. The prompt() instruction produces a string, and instead of storing this string in a variable, it is handed straight to the parseFloat() instruction which turns it into a decimal number. The string entered is never actually stored anyway, only the floating point number.


The alert() instruction


There is an alternative way to display messages. variables, numbers etc. on the screen which grabs your attention slightly more than document.write() does. This is the alert() instruction. It is called in a similar manner to document.write(), i.e. the item to be displayed are enclosed within brackets:


alert("The answer is " + answer);


This produces a grey box on the screen and a bleep noise. The box won't disappear or let you carry on with the program until you click on the OK button. You will notice that you don't need to preface the word alert with the word document or a full stop. This is because the alert() instruction is not a method belonging to the document object (Instead, it belongs to the window object, but that's another story )



The modulo operator


There is one mathematical operator that you haven't met yet. It is called modulo and is written as %. It gives the remainder when a division is carried out. For instance, the following program displays the number 2 on the screen, as 17 divided by 3 gives the answer 5 with a remainder of 2.



document.write(17 % 3)



Modulo can be used with variables, expressions etc. - in fact anywhere that ordinary division is used. Please note that ordinary division will not simply produce the whole number part of the division, it will produce a decimal, so the first line of the following program will produce 4.347826 as the answer (in an alert box, of course), and the second line will produce 8 (the remainder when 100 is divided by 23).



var first = 100, second = 23;

alert(first / second);

alert(first % second);





Often you will need to include small messages inside your program which are not intended to be displayed on the screen, nor instructions to the computer, but just to remind you at a later date about how the program works. This is especially true if the program is long and complex, or if you want some other programmer to look at your code - you have to inform that person about any quirks of your program. Such reminders are called comments.


The most common way of inserting a comment into a program is by using two forward slashes, //, together (no spaces between them). Anything following that on the same line is ignored until the end of the line is reached. Then the browser starts taking notice again. Here is an example of a comment:


var x = 23; // tax rate

tax = turnover * x / 100; // Calculate tax paid

net_profit = turnover - tax;


The words 'tax paid' and 'Calculate tax paid' are ignored by the program. They are messages to any human looking at the JavaScript code. Please note, that if you put any instructions after // then they will also be ignored:


var x = 23; // tax rate tax = turnover * x / 100;

// Calculate tax paid

net_profit = turnover - tax;


In this case, the instruction that calculates the tax is ignored - the program assumes it is part of the comment. This example also shows that you can have a comment at the start of the line (i.e. the entire line is dedicated to the comment), or you can have a comment on a line which contains nothing else but spaces:


var rows = 30; // This line defines the number of rows

// of pixels in the image.