Java Reference
In-Depth Information
However, your fix() function instead returns it like this:
2.1
Change the fix() function so that the additional zeros are added where necessary.
Exercise 3 Solution
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head>
<title>Chapter 5: Question 3</title>
<script type=”text/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 type=”text/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 ch05_q3.htm.
The function declaration and the fi rst line remain the same as in the fix() function you saw earlier in
the chapter. However, things change after that.
Search WWH ::




Custom Search