Larger Text Normal Text Smaller Text

IT 180 Web Development I, Fall 2009

 

Lesson 15: Using JavaScript functions

Some function terminology

Functions are similar to methods.

Both carry out some specific task for you.

In JavaScript, methods are built into the language itself, while functions are written separately and made available for use.

Image: A function returns a single valueLike methods, functions must be provided with arguments - inputs that are used to determine the result of the function - in the parentheses following the function name.

The result is usually a single value, called the return value.

It is used in an expression the same way a numeric literal or variable would be used.

Libraries

A collection of pre-written functions that can be used in programs is called a library.

Just as you can go look up information in a book from a public library, you can use a function from a computer library to determine some result.

Some libraries are included with JavaScript.

You can add others that you or other programmers create.

The Math library of functions

The Math library of mathematical functions provides the functions that you would find on a scientific calculator, including the square root function as well as logarithmic, exponential, and trigonometric functions.

These functions all have names beginning with Math. .

This means that they are part of a JavaScript object named Math, but you can just think of it as part of their name.

Rounding to a whole number - Math.round()

The Math library includes a function named Math.round() that will round numbers for us.

It should be given one numeric argument, and it returns the input rounded to the nearest whole number.

The input can be an expression.

For example,

    Math.round( 3.14159265358 ) is 3
    Math.round( 8.707 ) is 9
    Math.round( 2.2 *3 ) is 7
    Math.round( parseFloat("Enter a number") ) depends on what is entered

Improved Karvonen Example

In the Karvonen formula example of the last lesson, some of the results had lots of digits after the decimal point - for example:

For training, your heart rate should be at least 122.19999999999999 beats per minute,
but it should not be over 138.60000000000002 beats per minute.

To improve the output, we will change the two statements:

  var low =  resting + 0.6 * HRR;

  var high =  resting + 0.8 * HRR;

to

  var low =  Math.round(resting + 0.6 * HRR);

  var high =  Math.round(resting + 0.8 * HRR);

The the complete example page demonstrates that you will always get whole numbers for the results. Try entering a variety of different values to check.

Rounding to a number of decimal places - the toFixed() method

We could use Math.round() to improve the output for the carpet calculation problem too.

But there are a couple of problems - for one, money is usually reported in dollars and cents, such as $75.45, not rounded to the nearest whole dollar.

The carpet store will lose if a price of $75.45 is rounded $75 - and the customer will lose if $75.65 is rounded to $76.

In JavaScript 1.5, there is a method called toFixed that will format a number to a designated number of decimal places.

It will add zeros as necessary.

It is applied to the number in the form

    number_being_formatted.toFixed(number_of_decimal_places)

The result is actually a string, not a number.

A number won't have the extra zeros displayed.

For example

    var amount = 1234.7654;
    alert(amount.toFixed(3)); //shows 1234.765
    alert(amount.toFixed(2)); //shows 1234.77 
    alert(amount.toFixed(7)); //shows 1234.7654000

Warning: The toFixed method is only available in JavaScript 1.5, not in earlier versions.

Hence it is only available in browser versions Netscape 6, IE 5.5, and newer versions or browsers.

If you are creating an application that needs to be be accessible to outdated browsers, you must use a different solution.

Rounding up and down - Math.ceil() and Math.floor()

Although rounding often is to the nearest amount, sometimes you need to always round up or down.

For example, suppose a calculation advises the consumer to purchase 10.0625 linear units of carpet.

This isn't practical for the store to measure and cut.

But if the amount is rounded to 10 units, it will not competely cover the area.

One solution is to always round UP.

The Math object includes functions called Math.ceil() and Math.floor().

Math.ceil always rounds up.

Math.floor always rounds down.

Example - Karpet Kalculator

As an example, let's work through an extended version of the carpet area calculation.

The problem

Suppose you are working at a carpet store.

The carpet comes in 2 unit (meters or yards) wide rolls.

It is sold by the linear unit at $23.95 per unit.

To help customers plan ahead, you want to create a web page for them.

The customer should be able enter the length and width of a room and find its area, the linear amount that must be purchased, and the cost.

Analysis

There are three steps to the calculations:

  1. first, find the area (length times width)
  2. then find the number of linear units to purchase.
    There are 2 square units of carpet per linear unit on the roll, so the amount to buy will be the area divided by 2.
  3. Calculate the cost as linear units * 23.95

So our computations will be

    area is calculated as length * width;
    linear units is calculated as area/2;
    cost is calculated as linear units * 23.95

The form

The length and width will need to be entered in text input boxes. The other amounts are all calculated.

There will need to be a textarea for displaying the result.

Outline

A very basic outline is:

  1. get room width from the form
  2. get room length from the form
  3. compute area as length * width
  4. compute linearUnits to purchase as area/2
  5. round the linearUnits to purchase UP using Math.ceil()
  6. compute cost as linearUnits * 23.95
  7. display results, showing the cost to two decimal places using .toFixed()

Variables

We will use variables

      length
      width
      area
      linearUnits
      cost

Implementation

The form will be named frmCarpet, the text inputs for length and width will be named txtLong and txtWide, and the textarea for output will be named araDisplay.

This is the event handler.

  //JavaScript program to calculate carpet purchases
  // 1. Get length - it should be a number, so use parseFloat
  var length = parseFloat(document.frmCarpet.txtLong.value);

  // 2. Get width - it should be a number, so use parseFloat
  var width = parseFloat(document.frmCarpet.txtWide.value);

  // 3. Compute area
  var area = length * width;

  // 4. Compute linear amount. ROund up.
  var linearUnits = Math.ceil(area / 2);

  // 5. Compute cost
  var cost = linearUnits * 23.95;

  //6. Display area, amount to purchase, and cost
  //   The \n creates a line break.  
  //   toFixed() shows a fixed number of decimal places.
  
  document.frmCarpet.araDisplay.value = 
          'Your room is ' + length + ' by '+ width + ' units.\n'  +
          'It will require '+ area.toFixed(1) + ' square units of carpet.\n' +
          'You should purchase ' + linearUnits + ' linear units at a cost of $' + cost.toFixed(2) + '.';

The complete example page demonstrates that you will always get whole numbers for the rates.

Test

Test it with the following dimensions. Make note of the results.

  1. 3 by 4
  2. 3.5 by 4.5
  3. 8 by 5
  4. 11 by 7

Spacing text - the \t tab

In JavaScript, \t represents the tab character when used in text output.

For example, test

alert('one \t two \t three');
alert('one \t two \t three \n one \t two \t\t three \t\t\t four');

The example modified

Modify the carpet calculator so the the user can enter several room sizes. Each time a calculation is requested, the line of results should appended to the textarea so the previous ones are still visible.

We will use tabs in the lines of text to approximate columns. (This doesn't work very well, but we don't have a better way.) The headings on the output wil be provided as the initial textarea value.

    <textarea name="araDisplay" rows="4" cols="60">       Length  Width   Area    Buy     Cost
    </textarea>

The calculations do not need to be changed.

Each new set of results is appended to the previous textarea value instead of replacing it.

   document.frmCarpet.araDisplay.value =
         document.frmCarpet.araDisplay.value  + 
         '\t' + length + '\t'  + width  + 
         '\t' + area.toFixed(1) + '\t' + linearUnits  +
         '\t$' + cost.toFixed(2) + '\n' ;

The computational steps of the JavaScript programs are not changed. Only the way the results are displayed is different.

Check the complete example page.

Comments to: chang@hood.edu
Last Modified: 17 November 2008. 09:15

 

Hood College Department of Computer Science: Course materials © 1997-2007 by Elizabeth Chang.


 
Valid CSS! Valid XHTML 1.0!