The possibilities are endless for the types of values that can be converted from one form to another. Script 17.10 shows just one example: how to convert kilometers to miles.
To convert kilometers to miles:
1. | var t,expr=prompt('Length in kilometers:',''), The bookmarklet starts by prompting the user for a length in kilometers (Figure 17.23). Figure 17.23. First, ask for the number to be converted.
|
2. | if(isNaN(parseFloat(expr))) Check to see if the user entered a numeric value. |
3. | {t=expr+' is not a number';} If not, set t to be an error message. |
4. | else{t='Length in miles is '+Math.round(expr*6214)/10000;} Otherwise, convert the value to miles and store it in t. |
5. | alert(t); Whether the input value is good or bad, we’ve stored the result in t. Here we display that result, as shown in Figure 17.24. |
✓ 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 bookmarklets with different conversions and then organize them all into folders in your Bookmarks or Favorites menu. Conversions can be just a mouse click away.
javascript:(function(){var t,expr=prompt('Length in kilometers:',''),if(isNaN(parseFloat(expr))){t=expr+' is not a number';}else{t='Length in miles is '+Math.round(expr*6214)/10000;}alert(t);})(); |
3.141.47.163