Javascript is a loosely typed language, which means it is possible to define a variable without specifying what type of data it holds (string, integer, floating point, etc.). This can cause problems if you think a particular value is a number when in fact it is a string. A string must be converted to a number to use it in calculations.
For example, when working with SCORM elearning software, scoring and performance data is stored in a Learning Management System as strings. If you need to do calculations with the data after retrieving it, the string data must be converted to integers or floating point type.
The parseInt() function can be used for this purpose. It parses a string and returns an integer. However use of the function without understanding the details can lead to unexpected results. If your string begins with a zero, the number will be evaluated in octal instead of decimal system. In Octal, 08, 09 are not valid numbers, and 010, 011, etc. will not represent the same values as they would in decimal system.
Ads by Google
Posted by ellen at September 19, 2007 12:04 PM
To ensure that the string is evaluated the way you want, specify the "radix" parameter, and make sure that the first character in the string can be evaluated as a number.
From the W3Schools article on parseInt() function:
parseInt(string, radix)
The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.
If the radix parameter is omitted, JavaScript assumes the following:
If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)
...
From the ECMAScript Language Specification (PDF)
- ...parseInt may interpret only a leading portion of the string as an integer value; it ignores any characters that cannot be interpreted as part of the notation of an integer, and no indication is given that any such characters were ignored.
When radix is 0 or undefined and the string's number begins with a 0 digit not followed by an x or X, then the implementation may, at its discretion, interpret the number either as being octal or as being decimal. Implementations are encouraged to interpret numbers in this case as being decimal.