Previous Page
Next Page

Converting Values

The possibilities are endless for the types of values that can be converted from one form to another. Script 17.11 shows just one example: how to convert kilometers to miles.

Script 17.11. You can create bookmarklets for almost any kind of unit conversion. This script converts kilometers to miles.

javascript:var expr=prompt('Length in kilometers:','');if(isNaN(parseFloat(expr))) {alert(
expr+' is not a number')}else {alert('Length in miles is '+Math.round (expr*6214)/10000);}

To convert kilometers to miles:

1.
javascript:var expr=prompt('Length in kilometers:','');



The bookmarklet starts by prompting the user for a length in kilometers (Figure 17.20).

Figure 17.20. First, ask for the number to be converted.


2.
if(isNaN(parseFloat(expr)))



Check to see if the user entered a numeric value.

3.
{alert(expr+' is not a number')}



If not, put up an error message.

4.
else{alert('Length in miles is '+Math.round(expr*6214)/10000);}



Otherwise, convert the value to miles and display it as an alert, as shown in Figure 17.21.

Figure 17.21. JavaScript returns the result of the conversion.


Tips

  • It's a straightforward process to adapt this script into any kind of conversion you need. Just change the label in step 1, and replace the math expression in step 4 to the correct expression for the particular conversion you're looking for.

  • You can make up a bunch of book- marklets with different conversions and then organize them all into folders in your Bookmarks or Favorites menu. Conversions can be just a mouse click away.



Previous Page
Next Page