Type Conversion



index
Disabled back button Next Section
printable version

Section 1: Typing

JavaScript (ECMAScript) is a loosely typed language.

This does not save the programmer from needing to think about the actual type of values that they are dealing with.

A very common error in browser scripting, for example, is to read the value property of a form control into which the user is expected to type a number and then add that value to another number.

That problem is exacerbated by the dual nature of the + operator being used for both numeric addition and string concatenation.

Section 2: Converting Values to Numbers

Converting values to numbers, especially strings to numbers (since everything entered in a form field is read as a string), is a common requirement.

There are many approaches that can be used to convert values to numbers:

var numValue = stringValue - 0;

var numValue = stringValue * 1;

var numValue = stringValue / 1;

Recommended option: the unary + operator (positive sign) type-converts its operand to a number, and because it does not do any additional mathematical operations, it is the fastest method for type-converting a string into a number.

var numValue = +stringValue;

While unary + is the fastest method for converting a string to a number, yet another method is available that uses the Javascript type-conversion algorithms. The Number constructor can be called with the string value as its argument and its return value is a number representing the result of the type-conversion.

var numValue = Number(stringValue);

The Number constructor is the slowest of the type-converting methods but when speed is not an overriding consideration its use does produce the clearest source code.

Section 3: Parsing to Numbers

parseFloat

An alternative method of converting a string into a number is to use one of the global functions designed to parse a string and return a number.

The string parsing functions read the string character by character until they encounter a character that cannot be part of the number, at which point they stop and return a number based on the characters that they have seen that can be part of the number.

With parseFloat, empty strings return NaN along with strings that cannot be subject to numeric interpretation.

parseInt

The parseInt function works in a similar way to parseFloat except that it is trying to interpret its string argument into an integer, and as a result recognizes fewer character as possible candidates to be part of that number.

Beware: because of the number format used by JavaScript, numbers are often represented by near approximations.

For rounding numbers to integers one of Math.round, Math.ceil and Math.floor are preferable.

Adapted from Javascript Type-Conversion