Basic mathematical calculations

This script calculates various circle and sphere properties based on a radius that the user enters, and updates multiple text fields with the results when the user clicks a "calculate" button.

Programming Issues

Our calculate() function is called when the push button is clicked, generating the onclick event. Our basic forms 1 example shows how to update an HTML text box. The calculate() function reads the value of the radius entered in the first text box, and then populates the remaining text boxes with the various properties calculated from that radius.

The primary issue in this example is calculating the properties in question. JavaScript's Math object contains a number of built-in methods (such as for calculating powers, rounding numbers, generating random numbers) and values (such as pi and e). We access these methods and values using the name of the object (Math — note this must begin with a capital letter), a period, and the name of the method or value. For instance, to access the value of pi, we use Math.PI.

In addition to Math.PI, in this example we use two methods of the Math object: Math.pow, for calculating powers, and Math.round, for rounding numbers. The circumference of a circle, for instance, is calculated by the formula pi·r², so we use Math.pow(form.radius.value,2) * Math.PI.

The Math.round method only rounds to integers — we cannot tell it, for instance, to round to 3 decimal places. To accomplish this we use the following construct: Math.round(x * 1000) / 1000, where x is the number we want to round to 3 decimal places.

Note: a method is very similar to a function, except the former is part of an object, whilst the latter stands alone.

Demonstration

Radius cm
Diameter cm2
Circumference cm
Area cm2
Volume cm3

Source and Downloads