Java Reference
In-Depth Information
</script>
</body>
</html>
  
Save the page as ch5_example5.html . When you load the page into your browser, you will be presented
with two prompt boxes. In the first, enter the number for which you want to fix the number of decimal
places (for example, 2.2345) . In the second, enter the number of decimal places you want fixed (for
example, 2 ). Then the result of fixing the number you have entered to the number of decimal places
you have chosen will be written to the page, as shown in Figure 5-5. For the example numbers, this
will be 2.23 .
figure 5-5
You first define the function fix() . This function will fix its fixNumber parameter to a maximum of its
decimalPlaces parameter's number of digits after the decimal place. For example, fixing 34.76459 to a
maximum of three decimal places will return 34.765 .
The first line of code in the function sets the variable div to the number 10 raised to the power of the
number of decimal places you want:
function fix(fixNumber, decimalPlaces) {
var div = Math.pow(10,decimalPlaces);
Then, in the next line, you calculate the new number:
fixNumber = Math.round(fixNumber * div) / div;
Search WWH ::




Custom Search