Java Reference
In-Depth Information
What the code Math.round(fixNumber * div) does is move the decimal point in the number that you
are converting to after the point in the number that you want to keep. So for 2.2345, if you want to
keep two decimal places, you convert it to 223.45. The Math.round() method rounds this number to
the nearest integer (in this case 223) and so removes any undesired decimal part.
You then convert this number back into the fraction it should be, but of course only the fractional part you
want is left. You do this by dividing by the same number ( div ) that you multiplied by. In this example,
you divide 223 by 100 , which leaves 2.23 . This is 2.2345 fi xed to two decimal places. This value is
returned to the calling code in the line
return fixNumber;
}
In the body of the page, you use two prompt boxes to get numbers from the user. You then display the
results of using these numbers in your fix() function to the user using document.write().
Number Object
As with the String object, Number objects need to be created before they can be used. To create a
Number object, you can write the following:
var firstNumber = new Number(123);
var secondNumber = new Number('123');
However, as you have seen, you can also declare a number as primitive and use it as if it were a Number
object, letting JavaScript do the conversion to an object for you behind the scenes. For example:
var myNumber = 123.765;
As with the String object, this technique is preferable so long as it's clear to JavaScript what object you
expect to have created in the background. So, for example,
var myNumber = “123.567”;
will lead JavaScript to assume, quite rightly, that it's a string, and any attempts to use the Number
object's methods will fail.
You'll look at just the toFixed() method of the Number object because that's the most useful method
for everyday use.
The toFixed() Method
The toFixed() method cuts a number off after a certain point. Let's say you want to display a price
after sales tax. If your price is $9.99 and sales tax is 7.5 percent, that means the after-tax cost will be
$10.73925. Well, this is rather an odd amount for a money transaction — what you really want to do is
fi x the number to no more than two decimal places. Let's create an example.
var itemCost = 9.99;
var itemCostAfterTax = 9.99 * 1.075;
document.write(“Item cost is $” + itemCostAfterTax + “<br />”);
Search WWH ::




Custom Search