### Strings To Numbers: Data Type Conversion

The first thing you need to understand about string to number conversion is that JavaScript's built-in conversion methods do NOT validate the string for proper number format. The methods assume the string holds a perfect number, ready for conversion.

#### The Addition Operator: THE BIG GOTCHA

When attempting to add number data types to numbers stored as strings, your script will produce baffling results if you forget to first convert the string data to numbers. One example of this common mistake is when attempting to add numbers which came from form fields. The mistake is forgetting that form field values are string data types, not number data types.

Since the arithmetic operator (+) is the same symbol as the string operator (+), when one of the operands is a string value, the JavaScript engine will only evaluate the expression as a string, concatenating the number to the string.

This means that the number and the string-number will not be added together mathematically, but instead pieced together to form a new string.
```
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
```

#### Forced Conversion and Testing a Returned Value (Validation)

You can force conversion to number data type by performing a mathematical operation on a string. Simply subtract zero or multiply by 1 (DON'T add anything!) to force conversion, and cause the expression to be evaluated by the interpreter. The returned value will either by a valid number or NaN (not a number). If the returned value is NaN, you know the string did not contain a valid number. The following example demonstrates this technique.
```
this.form.elements.value * 1

// if form value == "4" output is 4
// if form value == "R" output is NaN

```

Since numbering systems are vast - versioning systems, naming conventions, date formats, money formats, phone number/zip code formats, etc. etc., it would be extraneous, if not futile, to try to write a pre-conversion validation script attempting to cover all formats and conventions. Instead, search the web for a regular expression script which suits your exact validation needs, then get on to conversion.

View Source | Home | Contact