ADDITION
As you can see from the preceding section, this automatic conversion feature may be a problem when you want to add numbers together instead of concatenating them. JavaScript includes features that allow you to work around this issue.
Note that this is only a problem when you're using the +
operator. Because JavaScript uses the same operator for two different
purposes (addition and string concatenation), it's not always clear to
JavaScript whether data should be considered a number or a string. If you use
any other mathematical operators in a statement, JavaScript makes the
appropriate conversions, as in the first example in the previous section.
You can also use any of the methods associated with JavaScript's built-in
Math object to make sure JavaScript recognizes data as numeric;
for example, you can use the round method to round a number to
the closest integer value:
var a = "5.1"; // the value of a is the string "5.1" var a = Math.round (a); // the value of a is now 5, and JavaScript treats it as numerical data
If the decimal portion is greater than or equal to .5, it's rounded up; otherwise, it's rounded down.
You can also use the parseInt () function to convert a string to
a number; for example:
var a = "5.1"; // the value of a is the string "5.1" var a = parseInt (a); // the value of a is now 5, and JavaScript treats it as numerical data
parseInt() converts a string to an integer. It can also take
numbers from the beginning of a string and leave the rest; for example,
parseInt ("123abc"); returns the numeric value 123.
And finally, a simple way to convert strings to numbers is to multiply them by 1; for example:
var a = 2; // a is a number var b = "5"; // b is a string b = b * 1; // b is now a number var c = b + a; // the value of c is now 7
Moving On
This lesson showed you how to add scripts to HTML pages. You also learned important terminology that'll come in handy in later lessons. In the Lesson 3, you'll see how automatic conversion can be important when obtaining numeric information from users. But, no problem, right? You can now apply the techniques you learned in this lesson to make sure that numbers are treated as numbers.
Before you move on to Lesson 3, don't forget to do the assignment and take the quiz. In addition, visit the Message Board to find out what your fellow students are talking about.
