<html>
<head>
<script language=JavaScript>
function fix(fixNumber, decimalPlaces)
{
var div = Math.pow(10,decimalPlaces);
fixNumber = new String(Math.round(fixNumber * div) / div);
If (fixNumber.lastIndexOf(".")==1)
{
fixNumber = fixNumber + ".";
}
var zerosRequired = decimalPlaces 
(fixNumber.length  fixNumber.lastIndexOf(".")  1);
for (; zerosRequired > 0; zerosRequired)
{
fixNumber = fixNumber + "0";
return fixNumber;
}
</script>
</head>
<body>
<script language=JavaScript>
var number1 = prompt("Enter the number with decimal places you want to fix","");
var number2 = prompt("How many decimal places do you want?","");
document.write(number1 + " fixed to " + number2 + " decimal places is: ");
document.write(fix(number1,number2));
</script>
</body>
</html>
Save this as ch04_q3.htm.
The function declaration and the first line remain the same as the fix() function we saw earlier in the chapter. However, things change after that.
We create the fixed number as before, using Math.round(fixNumber * div) / div. What is new is that we pass the result of this as the parameter to the String() constructor that creates a new String object, storing it back in fixNumber.
Now we have our number fixed to the number of decimal places required, but it will still be in the form 2.1 rather than 2.100 as required. Our next task is therefore to add the extra zeros required. To do this we need to subtract the number of digits after the decimal point from the number of digits required after the decimal point as specified in decimalPlaces. First, to find out how many digits are after the decimal point we write
(fixNumber.length  fixNumber.lastIndexOf(".")  1)
For our number of 2.1, fixNumber.length will be 3. fixNumber.lastIndexOf(".") will return 1; remember that the first character is 0, the second is 1, and so on. So fixNumber.length  fixNumber.lastIndexOf(".") will be 2. Then we subtract 1 at the end leaving a result of 1, which is the number of digits after the decimal place.
The full line is
var zerosRequired = decimalPlaces 
(fixNumber.length  fixNumber.lastIndexOf(".")  1);
We know the last bit (fixNumber.length  fixNumber.lastIndexOf(".")  1) is 1 and that the decimalPlaces parameter passed is 3. 3 – 1 leaves two zeros required to be added.
Now that we know how many extra zeros are required, let's add them.
for (; zerosRequired > 0; zerosRequired)
{
fixNumber = fixNumber + "0";
}
Now we just need to return the result from the function to the calling code.
return fixNumber;
