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
fixed to two decimal places. This
value is returned to the calling code in the line:
return fixNumber;
}
Next, 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()
.
This example is just that—an example. In a few minutes, you learn about the
Number
object's
toFixed()
method, which does the same thing as the
fix()
function.
number objects
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 look at just the
toFixed()
method of the
Number
object because that's the most useful method
for regular 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 fix the number to no more than two decimal places. Let's create an example: