Welcome to the third part of a six-part series on building a web page calculator. In the previous part I gave you the skeletons of our two standard calculator functions. But there are fine details to these functions that we have to examine and appreciate. We start with the showNum() function.

Function Details for a Web Page Calculator (Page 1 of 5 )

Details of the showNum() Function

The function is called when you click a digit button, the decimal point, or the Memory Retrieve (MR) button. The global variable for this function is

var showNumCalledOnce = false;

I will explain the use of this while going into the details.

There are three code segments for this function.

The First Code Segment

The first code segment is:

//remove the initial zero in the display unless the user began by typing the decimal point.

if (showNumCalledOnce == false)

{

if (!((ID == "B0")||(ID == "BPOINT")))

document.getElementById('CI1').value = "";

}

showNumCalledOnce = true;

//Clear the display (Input Text Control) if -, +, X or / button has been clicked

if (toClearDisplay == true)

{

document.getElementById('CI1').value = "";

//reset the variable, toClearDisplay

toClearDisplay = false;

}

When the calculator opens, the digit zero is on the display. This digit was inserted by the showCalc() function, which is not part of any of the two calculator functions. As soon as you type (click) a digit you need for evaluation, this zero has to be replaced by the digit you typed.

The calculator showNum() function is called whenever you type any digit. After the calculator has just opened on the web page, the first digit you type calls this function. The first statement in the function is an “if” statement. It has an inner “if” statement. The code line that removes the zero is in the inner “if” statement.

document.getElementById('CI1').value = "";

The line replaces the zero with an empty string. However, there is a condition to be fulfilled. In normal life, if a number begins with a decimal point, the number is usually preceded by a zero, e.g. 0.285. The convention with our calculator is that if the user starts by typing a decimal point, the initial zero on the display should remain. Some people may have to type a number, say 23, and they would type 023. Also some people would prefer to type .285 as 0.285. So this code segment allows you to start typing a number by pressing zero. Because of this situation, you have the following line as the if condition

if (!((ID == "B0")||(ID == "BPOINT")))

If you have the habit of typing 23 as 023, the calculator will allow you to type the 3 digits. However you will see only the 2 important digits (23) on the display. Down in the code I remove the preceding zero. It is because of these reasons that you have the above expression.