|
|
|
Converting strings to integer is an everyday task for Web developers. Those who have used JavaScript to validate forms already know the basics. JavaScript allow a simple function to eliminate redundant tasks.
parseInt ( ): JavaScript provides a very simple function just fit for our intended use: var myInteger = parseInt (aString); After getting the converted integer in the myInteger variable, you can use it for normal operations like manipulating it arithmetically. The following simple code shows a textbox; it reads the contents on press of a button and shows half of the number entered. <html> If you try this code you may notice a strange thing: it treats "08" or "09" as 0. This happens for all invalid inputs. The answer to this question lies in a simple insight into the way JavaScript handles integers. (The following statement is true for C / C++ and Java, too.) An integer can be represented in three different ways: in base 8 (octal), base 10 (decimal) and base 16 (hexadecimal). A starting zero indicates an octal number which can be anything from 0 to 7 but not 8 or 9. Similarly, a hexadecimal number is indicated by a starting "0x" followed by a number that can be anything from 0 to F. The solution to the problem is very simple. Since "08" means an octal number because of a starting 0, parseInt returns a zero for 8. Now, parseInt accepts a second optional parameter, which is the base of the number. You can forcefully tell it to treat the number as a decimal one by sending a second parameter 10. Revise the code as follows: <html> Go To Page: 1
The copyright of the article Parsing Integers in JavaScript: Problems and Solutions for Invalid Inputs in JavaScript is owned by . Permission to republish Parsing Integers in JavaScript: Problems and Solutions for Invalid Inputs in print or online must be granted by the author in writing.
|
|
|
|
|
|
|
|