Thursday, November 05, 2015

Numbers That Self-Multiply and How to Deal with Them

Blog Entry #352

Next up in the Java Goodies Calendars, Clocks, and Calculators sector is a "Square Root in the Status Bar" script, which we will discuss in today's entry. Authored by Tom Hammond in 1998, the Square Root in the Status Bar script determines the (principal) square root of a user-inputted number and then writes the root to the browser window's status bar. The script code may be accessed at Joe's JavaScript Goodies site.

You'll need an old-school browser to see the script's effect because

*modern browser windows do not have status bars*; we'll route the root to a more suitable holder in due course.

(As we'll see below, the statusroot.txt code is pretty simple; however, every script has a story that deserves to be told, does it not? More importantly, when I come across one of these scripts whose output is problematic in some way,

*I can't let that sit, I've just got to do something about it*- that's how I roll, and that's why I'm writing this post.)

**The script**

The script's renderable part (there's no clear demarcation between the document head and body) begins with some instructions for the user:

`<center>`

<i><big><b>Instructions:</big></i><br>

First of all enter a number into the text box, then click the 'Square Root' button and look at the little status bar at the bottom of the screen to see what the square root of the number you entered is!

• To horizontally center the script display (my demo below is left-justified), use a

`<div style="text-align:center;"> ... </div>`

container as opposed to a `<center>`

element.• To enlarge the

*Instructions:*font size, use a

`<span style="font-size:larger;"> ... </span>`

container as opposed to a `<big>`

element.• Note that the

`</b>`

tag is missing.The instructions are followed by a name=feedbackForm form

`<form name="feedbackForm">`

<input type="text" name="number" value="" size="8">

<input type="button" value="Square Root" onclick="display( );">

</form></center>

that contains

(1) a name=number text input in which the user enters a number to be square-rooted and

(2) a button that when clicked calls a display( ) function

```
<script language="javascript">
function display(number) {
window.status = "The square root of " + document.feedbackForm.number.value + " is " + Math.sqrt(document.feedbackForm.number.value); }
</script>
```

that Math.sqrt( )s the number field's value, appends the sqrt( ) return to a

The square root of document.feedbackForm.number.value is

string, and loads the resulting string into the status bar if the status bar is present.

• The display( ) function's number parameter is unnecessary: it fortunately doesn't affect the document.feedbackForm.number.value getter although you should still get rid of it.

**Modifications**

The display( )-containing

`<script>`

element includes a readme-type comment that concludes with:`/* If anyone has any ideas, use 'em! */`

Let's do that, shall we?

A new home

Obviously, the sqrt( ) return should be written to the page vis-à-vis the status bar, and a

`<samp>`

element is a semantically appropriate place to park it:`Your square root is: <samp id="rootSamp"></samp>`

...

document.getElementById("rootSamp").textContent = Math.sqrt(document.feedbackForm.number.value);

Nonnegative numbers only, please

The sqrt( ) method returns NaN for arguments that are not nonnegative numbers; I prefer to intercept such arguments before the fact:

```
var rInput = document.feedbackForm.number;
if (isNaN(rInput.value) || rInput.value === "") {
window.alert("Please enter a nonnegative number into the text box.");
rInput.value = ""; rInput.focus( ); return; }
if (rInput.value < 0) {
window.alert("Nope, we're not gonna generate an imaginary number for you.")
rInput.value = ""; rInput.focus( ); return; }
```

• Regarding the first if statement, the

`isNaN(rInput.value)`

subcondition flags all non-numeric values (including true and false, null, and undefined) except for the empty string with the OS X browsers on my computer; a `rInput.value === ""`

subcondition is necessary to intercept a blank number field.• It is left to the reader as an exercise to have the script output an imaginary number for a negative number input.

A truncated root

The following code will stop a sqrt( ) return at three places past the decimal point if it goes beyond that:

`var root = Math.sqrt(rInput.value);`

if (/\.\d{4,}$/.test(root)) root = root.toFixed(3);

document.getElementById("rootSamp").textContent = root;

The \.\d{4,}$ regular expression matches a floating-point number having four or more post-decimal point digits; if the root test( )-matches the expression, then it is toFixed( ) at the thousandths place.

**Demo**

It's time to roll out a demo - try it out with any input you like.

Instructions:

(1) Enter a nonnegative number (either an integer or a floating-point number) into the text box.

(2) Click the 'Square Root' button to display the square root of your entered number to three or fewer places past the decimal point.

√

Your square root is:

#### Other extractions

Before wrapping up this post, I should note that the JavaScript Math object has a pow( ) method via which we can determine the square root or any other type of*n*th root (a cube root, a fourth root, etc.) of a number - check out the Examples on the Mozilla Math.pow( ) page.

We'll take on something a bit more challenging next time, I promise.

Actually, reptile7's JavaScript blog is powered by Café La Llave. ;-)