Strings To Numbers: Data Type Conversion

When attempting to add number data types to numbers stored as strings, beware that your script will produce surprising results unless you first do a little data type conversion. An example of this all too common mistake made by newcomers is when attempting to add numbers which came from form fields.

As you know from the first strings lesson, form field values are strings. Since the arithmetic operator is the same symbol as the string operator, and one of the operands is a string value, the interpreter must make a decision as to how to evaluate the expression.

Lucky for us, that decision is always the same: anytime a string and string operator are involved with a number, the JavaScript engine will interpret the "+" operator as the string operator, and concatenate the number with the string. This means that the number and the string masquerading as a number will not be evaluated as a mathematical expression.
2 + 2    // result is 4
2 + "2"    // result is 22
"2" + "2"    // result is 22
2 + 2 + "2"    // result is 42

Conversion Methods

To be sure your string-containing expression is evaluated properly, use a couple of very handy methods for converting strings to numbers - parseInt() for integers (whole numbers) and parseFloat() for floating point numbers (contain decimals).
parseInt("2") + parseInt("2")    // result is 4
2 + parseInt("2")    // result is 4



>>String Literals and String Variables
>>Nesting Quotes And The Escape Character
>>String Concatenation and String Operators
>>Creating Line Breaks
>>Strings To Numbers: Data Type Conversion
>>Strings and The Write Method



Home | Contact