You run an online music service where customers rate each song. You
aggregate all the
customer ratings and average them, awarding a song from zero to five
stars. Usually, averaging
produces a fraction. You need to round it to the nearest integer so you
can translate the number
into stars. Suppose the average has been assigned to the variable
scoreAvg. Here's the code
that rounds it to the nearest integer.
var numberOfStars = Math.round(scoreAvg);
Things to keep in mind:
Math. is how all math functions begin. The "M" must be capped.
The function rounds up when the decimal is .5. It rounds 1.5 to 2, 2.5
to 3, etc. It rounds -
1.5 to -1, -2.5 to -2, etc.
When the result is assigned to a new variable, as in the example above,
the unrounded
number enclosed in parentheses is preserved. But you can assign the
rounded number to the
original variable, and the unrounded number will be replaced by the
rounded number.
scoreAvg = Math.round(scoreAvg);
Instead of a variable, you can enclose a literal number in the
parentheses.
var scoreAvg = Math.round(.0678437);
To force JavaScript to round up to the nearest integer, no matter how
small the fraction,
use ceil instead of round. The following code rounds .000001, which
would normally round
down to 0, up to the nearest integer, 1.
var scoreAvg = Math.ceil(.000001);
ceil stands for "ceiling." It rounds .000001 up to 1, -.000001 up to 0,
1.00001 up to 2,
and so on.
To force JavaScript to round down to the nearest integer, no matter how
large the
fraction, use floor instead of round. The following code rounds .999999,
which would
normally round up to 1, down to 0.
var scoreAvg = Math.floor(.999999);
floor rounds .999999 down to 0, 1.9 down to 1, -.000001 down to -1, and
so on.
Suppose you want to simulate the throw of a die. In the simulation, you
want it to
randomly come up 1, 2, 3, 4, 5, or 6. The first step is to ask
JavaScript to generate a random
number. (Well, it's almost random, technically known as pseudo-random,
but it's close enough
to random for most purposes.)
The following code generates a pseudo-random number, with 16 decimal
places, ranging
from 0.0000000000000000 through 0.9999999999999999 and assigns it to the
variable
randomNumber.
var randomNumber = Math.random();
The function always delivers a 16-place decimal that ranges from
0.0000000000000000
to 0.9999999999999999. We can convert the decimal to an integer by
multiplying by one
hundred quadrillion (1 followed by 17 zeroes):
0.0000000000000000 * 100000000000000000 = 0
0.7474887706339359 * 100000000000000000 = 7474887706339359
0.9999999999999999 * 100000000000000000 = 9999999999999999
Trillions of possible numbers are more than we need in our virtual die
throw. We just
want six possible numbers, 1 through 6. So instead of multiplying by a
hundred quadrillion, our
first step is to multiply the giant decimal by 6.
0.0000000000000000 * 6 = 0
0.7474887706339359 * 6 = 4.7474887706339359
0.9999999999999999 * 6 = 5.9999999999999994
Intuition may tell you that you can finish the job by rounding, but that
doesn't work out
mathematically. Because nothing rounds up to 0 and nothing rounds down
to 6, the numbers in
the middle, which are reached both by rounding up and rounding down,
will come up almost
twice as often. But we can give all the numbers an equal chance if we
add 1 to the result, then
round down. Here's the code for our virtual die throw.
1 var bigDecimal = Math.random();
2 var improvedNum = (bigDecimal * 6) + 1;
3 var numberOfStars = Math.floor(improvedNum);
This is what happens in the code above, line by line:
1. Generates a 16-place decimal and assigns it to the variable
bigDecimal.
2. Converts the 16-place decimal to a number ranging from
0.0000000000000000 through
5.9999999999999999, then adds 1, so the range winds up
1.0000000000000000 through
6.9999999999999999. This number is assigned to the variable improvedNum.
3. Rounds the value represented by improvedNum down to the nearest
integer that ranges
from 1 through 6.
Sometimes JavaScript seems to read your mind. For example, suppose you
write...
var currentAge = prompt("Enter your age.");
...JavaScript assigns the user's answer to currentAge as a string. Her
entry, let's say
32, may look like a number to you, but to
JavaScript it's a string: "32".
Nevertheless, suppose you write...
1 var currentAge = prompt("Enter your age.");
2 var yearsEligibleToVote = currentAge - 18;
In the above code, the value assigned to the variable currentAge is a
string, because it
comes from a user's prompt response. But in line 2, when the variable
appears in an arithmetic
expression, the value is automatically (and temporarily) converted to a
number to make the
math work.
Similarly, if you ask JavaScript to divide "100" by 2 or multiply "2.5"
by 2.5, JavaScri
pt seems to understand that you want the string
treated as a number, and does the math. You
can even ask JavaScript to multiply, divide, or subtract using nothing
but strings as terms,
and JavaScript, interpreting your intentions correctly, does the math.
var profit = "200" - "150";
In the statement above, the two strings are treated as numbers because
they appear in a
math expression. The variable profit, in spite of the quotation marks,
is assigned the number
It probably goes without saying that the string you ask JavaScript to do
math on has to be
a number contained in quotes, like "50", not letter characters. If you
write...
var profit = "200" - "duck";
...an alert will display saying "NaN" meaning "not a number." No mystery
here. How can
200 minus "duck" be a number?
You may recall from a previous chapter that when you mix strings and
numbers in an
expression involving a plus, JavaScript does the opposite of what you
see in the examples
above. Rather than converting strings to numbers, JavaScript converts
numbers to strings.
Rather than adding, it concatenates.
var result = "200" + 150;
In the statement above, JavaScript, seeing the string "200" and the
number 150, resolves
the conflict by converting 150 to a string: "150". Then it concatenates
the two strings. The
variable result is assigned "200150". If the + in the expression were
one of the other
arithmetic operators(-, *, or /), JavaScript would convert the string
"200" to the number 200
and do the math.
You can see there's going to be a problem with the following code.
1 var currentAge = prompt("Enter your age.");
2 var qualifying Age = currentAge + 1;
The code above has an unintended consequence. The string represented by
currentAge is
concatenated with 1 that has been converted to "1". Example: if the user
enters "52,"
qualifyingAge is assigned not 53 but "521".
If you want to do addition, you must convert any strings to numbers.
1 var currentAge = prompt("Enter your age.");
2 var qualifyingAge = parseInt(currentAge) + 1;
Line 2 converts the string represented by currentAge to a number before
adding 1 to it
and assigning the sum to qualifyingAge.
parseInt converts all strings, including strings comprising
floating-point numbers, to
integers. And shocking but true: It it doesn't round. It simply lops off
the decimals. In the
following statement, myInteger is assigned not 2 as you might expect,
but 1.
var myInteger = parseInt("1.9999");
To preserve any decimal values, use parseFloat. In the following
statement
myFractional is assigned 1.9999.
var myFractional = parseFloat("1.9999");
To minimize confusion, coders sometimes prefer to do explicit, manual
conversions even
when JavaScript doesn't require them, as in mixing a string and a number
in a multiplication
operation.
In the last chapter you learned to use parseInt to convert a string
representing a number
into an integer. And you learned to use parseFloat to convert a string
representing a number
into a floating-point number. You can finesse the distinction between
integers and floatingpoint
numbers by using Number. This handy
conversion tool converts a string representing
either an integer or a floating-point number to a number that's
identical to the one inside the
parentheses.
The following code converts the string "24" to the number 24.
1 var integerString = "24"
2 var num = Number(integerString);
The following code converts the string "24.9876" to the number 24.9876.
1 var floatingNumString = "24.9876";
2 var num = Number(floatingNumString);
Suppose your code has done an arithmetic calculation that yielded a big
number. Now you
want to present the result of the calculation to your user. But before
you display the number,
you want to format it with commas so it's readable. In order to do that,
you'll have to convert
the number to a string. This is how you do it.
Converting a number to a string, perhaps so you can format it, is
straightforward.
1 var numberAsNumber = 1234;
2 var numberAsString = numberAsNumber.toString();
The code above converts the number 1234 to the string "1234" and assigns
it to the
variable numberAsString.
The price of the item is $9.95. The sales tax is 6.5% of the price. You
combine the two
numbers to get the total.
var total = price + (price * taxRate);
The variable total now has a value of 10.59675.
But that isn't what you're going to charge the customer, is it? You're
going to charge her an
amount rounded off to two decimal places: $10.60.
Here's how to do it.
var prettyTotal = total.toFixed(2);
The statement above rounds the number represented by total to 2 places
and assigns the
result to the variable prettyTotal. The number inside the parentheses
tells JavaScript how
many places to round the decimal to.
Now add a dollar sign, and you're all set.
var currencyTotal = "$" + prettyTotal;
To shorten a number to no decimals, leave the parentheses empty.
var prettyTotal = total.toFixed();
Unfortunately, the toFixed method comes with a surprise inside. If a
decimal ends in 5, it
usually rounds up, as you would expect. But, depending on the browser,
sometimes it rou nds
down! If, for example, you apply the method to 1.555, specifying 2
decimal places, it may give
you "1.56". Or it may produce "1.55".
There are sophisticated ways to address the problem. Here's an inelegant
fix that uses
methods you already know and understand.
1 var str = num.toString();
2 if (str.charAt(str.length - 1) === "5") {
3 str = str.slice(0, str.length - 1) + "6";
4 }
5 num = Number(str);
6 prettyNum = num.toFixed(2);
If the decimal ends in a 5, the code changes it to a 6 so the method is
forced to round up
when it should. Here's what's happening, line-by-line:
1. Converts the number to a string and assigns it to the variable str.
2. Checks to see if the last character is "5".
3. If so, slices off the "5" and appends "6".
4. --
5. Converts it back to a number.
6. Rounds it to 2 places.