Java Reference
In-Depth Information
You create the fi xed number as before, using Math.round(fixNumber * div) / div. What is new is
that you pass the result of this as the parameter to the String() constructor that creates a new String
object, storing it back in fixNumber.
Now you have your number fi xed to the number of decimal places required, but it will still be in the form
2.1 rather than 2.100, as required. Your next task is therefore to add the extra zeros required. To do this
you need to subtract the number of digits after the decimal point from the number of digits required after
the decimal point as specifi ed in decimalPlaces. First, to fi nd out how many digits are after the decimal
point, you write this:
(fixNumber.length - fixNumber.lastIndexOf(“.”) - 1)
For your number of 2.1, fixNumber.length will be 3. fixNumber.lastIndexOf(“.”) will return 1;
remember that the fi rst character is 0, the second is 1, and so on. So fixNumber.length - fixNumber
.lastIndexOf(“.”) will be 2. Then you subtract 1 at the end, leaving a result of 1, which is the
number of digits after the decimal place.
The full line is as follows:
var zerosRequired = decimalPlaces -
(fixNumber.length - fixNumber.lastIndexOf(“.”) - 1);
You know the last bit (fixNumber.length - fixNumber.lastIndexOf(“.”) - 1) is 1 and that the
decimalPlaces parameter passed is 3. Three minus one leaves two zeros that must be added.
Now that you know how many extra zeros are required, let's add them.
for (; zerosRequired > 0; zerosRequired--)
{
fixNumber = fixNumber + “0”;
}
Now you just need to return the result from the function to the calling code.
return fixNumber;
Chapter 6
Exercise 1 Question
Create a page with a number of links. Then write code that fi res on the window load event, displaying
the href of each of the links on the page. (Hint: Remember that event handlers begin with on.)
Exercise 1 Solution
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
Search WWH ::




Custom Search