HTML and CSS Reference
In-Depth Information
Rounding Values
Online ordering is one of the most common uses of the Web and requires calculations of
monetary values. For example, suppose you needed to calculate a 2% sales tax on a cus-
tomer's purchase of an item that costs $25.49. One way of doing this is to use the follow-
ing code, which multiplies the price by the tax rate and stores the value in the tax variable:
var price = 25.49;
var taxrate = 0.02;
var tax = price*taxrate;
The tax value from this calculation is 0.5098, which is not an acceptable currency value.
You could use the toFixed() function discussed earlier to display the result to only two
decimal places. However, recall that the toFixed() function doesn't change a vari-
able's value, only how it is displayed. Instead, you need to round the actual value of the
tax variable to the hundredths digit. There are no Math methods for rounding values
to specific numbers of decimal places. To round a currency value to two digits, you first
must multiply the value by 100, apply the Math.round() method to round the value to
the nearest integer, and then divide that result by 100. For the tax rate example, 0.5098
multiplied by 100 is 50.98; that value rounded to the nearest integer is 51; and dividing
that number by 100 results in a currency value of $0.51. In JavaScript, this sequence of
operations can be placed in a single expression as follows:
Math.round(100*tax)/100;
In general, if n is the number of decimal places to which you want to round a value, you
multiply and divide the value by 10 n . You could use this fact to create a custom func-
tion to round values to a specified number of decimal places. The following code uses
the pow() method of the Math object to create a general rounding function that rounds
values to n decimal places:
function roundValue(value, n) {
return Math.round(Math.pow(10,n)*value)/Math.pow(10,n);
}
The roundValue() function multiplies the value variable by a power of 10, rounds it
to the nearest integer, and then divides it by the same power of 10. The end result is
the value variable rounded to the number of digits specified by the n parameter. The
roundValue() function also allows for a negative value for the n parameter. This has
the effect of rounding a value to the nearest ten, hundred, thousand, and so forth. For
example, the expression
roundValue(238414, -3)
rounds the value to the nearest thousand, returning a value of 238,000.
Converting Between Numbers and Text
Sometimes you might need to convert a number to a text string and vice versa. One way
to convert a number to a text string is by using the + operator to add a text string to a
number. For example, the following code uses the + operator to concatenate a numeric
value with an empty text string:
testNumber = 123; // numeric value
testString = testNumber + “”; // text string
The result is to create a text string containing the characters 123 .
Search WWH ::




Custom Search