# parseInt and isNan example

• 02-13-2014, 08:28 PM
Olive85
parseInt and isNan example
I am studying web development and at the moment I am learning Java and JS, so I thought this following simple code would be handy for newbies :)

Quote:

var age = prompt ('How old are you?'); //a text box will pop up asking the question, and the answer is saved in age
age = parseInt(age);// the user's answer, age, will be checked whether it's and integer or not.
if (isNaN(age))//isNan looks and decides whether the age is NOT a number
{
age = prompt("You have not entered a number yet, so how old are you? ");//if isNaN finds out that age doesn't contain a number then a new sentence will be displayed.
}
document.write('You are '+age+' years old.');//if an integer is stored , then the code will display the value that was originally entered.

• 02-13-2014, 09:25 PM
felgall
Prompt is obsolete - it used to be used for debugging. Newbies should NOT lear that command.

parseInt() takes two parameters as its purpose is to convert from one number base to another - for example parseInt('fe',16) returns 254. To convert a string to a number you should use the Number() function.

with isNaN() - in that instance where someone entered their age as '09' and had the parseInt convert that to 0 (since the 9 is not a valid octal number) the isNaN call will never return false since parseInt always returns a number even if it is zero.

document.write is even more obsolete than prompt() - you should never use document.write unless your target browser is Netscape 4 or earlier. Getting newbies to use alert() instead of document.write became common about 10 years ago and that was in turn replaced by getting them to use innerHTML about 5 years ago.

In other words - Newbies, if you are being taught to write code like this then you are in a History class and not a programming class. A JavaScript programming class would not teach any of that code. If the class is part of a course and you just need to pass the subject but are not interested in programming then by all means continue with the history class. If you want to learn programming then you need to swap to a better class (or get a more recent book if you are learning this on your own).

Instead of prompt() use a form.
There's no point using isNaN if you have already converted it to a number - test > 0 instead - or test before converting to a number.
• 02-13-2014, 10:12 PM
rnd me
i'm surprised you didn't push "use script". Is it because that would fix your qualm about parseInt? good to see your one-man anti-dialog campaign is still alive and kicking...
• 02-13-2014, 11:17 PM
Olive85
Quote:

Originally Posted by felgall
Prompt is obsolete - it used to be used for debugging. Newbies should NOT lear that command.

parseInt() takes two parameters as its purpose is to convert from one number base to another - for example parseInt('fe',16) returns 254. To convert a string to a number you should use the Number() function.

with isNaN() - in that instance where someone entered their age as '09' and had the parseInt convert that to 0 (since the 9 is not a valid octal number) the isNaN call will never return false since parseInt always returns a number even if it is zero.

document.write is even more obsolete than prompt() - you should never use document.write unless your target browser is Netscape 4 or earlier. Getting newbies to use alert() instead of document.write became common about 10 years ago and that was in turn replaced by getting them to use innerHTML about 5 years ago.

In other words - Newbies, if you are being taught to write code like this then you are in a History class and not a programming class. A JavaScript programming class would not teach any of that code. If the class is part of a course and you just need to pass the subject but are not interested in programming then by all means continue with the history class. If you want to learn programming then you need to swap to a better class (or get a more recent book if you are learning this on your own).

Instead of prompt() use a form.
There's no point using isNaN if you have already converted it to a number - test > 0 instead - or test before converting to a number.

Yeah, I am a uni student, and I have got JavaScript module for 9 weeks :)
• 02-14-2014, 12:54 AM
felgall
Quote:

Originally Posted by rnd me
i'm surprised you didn't push "use script". Is it because that would fix your qualm about parseInt? good to see your one-man anti-dialog campaign is still alive and kicking...

Every post I make at the moment pushes "use strict" - its currently a part of my signature.

Just because one of the examples I gave for parseInt assumes octal when "use strict" isn't used doesn't make it appropriate to use in place of Number() for converting strings to numbers.

An alternate example would be if 0x35 were entered as the age in the original code which the following code would treat as 53. Even with "use strict" parseInt will still accept hxadecimal numbers when the second parameter is omitted.
• 02-15-2014, 02:30 AM
glenngv
Quote:

Originally Posted by felgall
parseInt() takes two parameters as its purpose is to convert from one number base to another - for example parseInt('fe',16) returns 254. To convert a string to a number you should use the Number() function.

There's at least one instance where you would use parseInt()/parseFloat() instead of Number(). That is when you want to convert css dimensions/positions into numbers.

Code:

```parseInt(element.style.paddingLeft); parseFloat(element.style.left);```
• 02-15-2014, 06:06 AM
felgall
Quote:

Originally Posted by glenngv
There's at least one instance where you would use parseInt()/parseFloat() instead of Number(). That is when you want to convert css dimensions/positions into numbers.

Code:

```parseInt(element.style.paddingLeft); parseFloat(element.style.left);```

That is making use of the secondary effect of discarding any non-numeric part to the right of the number - in this case the dimensions - px, in, em % or whatever.

In that instance you really ought to enter 10 as the second parameterr when using parseInt as that function takes two parameters and not one.

As you really need to track what the rest of the field is so you can put it back if you are going to update the value that was retrieved then a regular expression might be shorter for extracting both parts. If you don't need the rest then using parseFloat is one character shorter as it does only take one parameter.

Of course since you need to keep track of the di
• 02-15-2014, 07:56 AM
rnd me
Quote:

Originally Posted by felgall
In that instance you really ought to enter 10 as the second parameterr when using parseInt as that function takes two parameters and not one.

why? the 2nd argument is optional on parseInt, and always has been. 10 is the default now anyway, which makes your advice especially untimely.

that aside, can you name any css dimension value that starts with a redundant leading "0" when pulled from style.xxx, or any browser that returns hex or octal CSS dimensions? you know, one that would "fool" parseInt into not just chopping off the non-digits and decimals?
of course not, css defines numbers as [0-9]+|[0-9]*\.[0-9]+

Maybe you something i don't, but until then, i'm calling BS. Dogmatic BS even, which is the worst kind...
• 02-15-2014, 08:04 PM
felgall
Quote:

Originally Posted by rnd me
why? the 2nd argument is optional on parseInt, and always has been. 10 is the default now anyway, which makes your advice especially untimely.

The whole point of using parseInt is for converting between number bases which means that when used for its intended purpose the second parameter will NEVER be 10.

Only when you misuse that function would you ever want it to use 10 as the second value.

My comment about it not being the best thing for extracting the number from a CSS dimension is that you then don't know whether the the size is px in em % or whatever. A better option is to use a regular expression that extracts both parts.

If paddingLeft is `3in` then `parseInt(element.style.paddingLeft);` will retrieve the 3. It doesn't retrieve the `in` so there's nothing to indicate that the 3 represents inches.
• 02-15-2014, 08:06 PM
felgall
Quote:

Originally Posted by rnd me
why? the 2nd argument is optional on parseInt, and always has been. 10 is the default now anyway, which makes your advice especially untimely.

The whole point of using parseInt is for converting between number bases which means that when used for its intended purpose the second parameter will NEVER be 10.

Only when you misuse that function would you ever want it to use 10 as the second value.

My comment about it not being the best thing for extracting the number from a CSS dimension is that you then don't know whether the the size is px in em % or whatever. A better option is to use a regular expression that extracts both parts.

If paddingLeft is `3in` then `parseInt(element.style.paddingLeft);` will retrieve the 3. It doesn't retrieve the `in` so there's nothing to indicate that the 3 represents inches.

Using parseInt like that was a simple solution back when all the measurements in the web page were done using px so that you knew that you just had to add px to the end to convert back but modern web pages don't use px for very much any more.

A better solution is

`var dim = /^(\d+)(\D*)\$/.exec(element.style.paddingLeft);`

which if the padding were 3in would return the 3 in dim[1] and the 'in' in dim[2]

Anyway the OP isn't using it like that so that it can be used to extract the numeric portion of 3in is irrelevant to the use they are making of it where Number is the correct function to use instead.

Quote:

Originally Posted by rnd me
i'm calling BS. Dogmatic BS even

Hello Mister Even - do you prefer to be called BS or Dogmatic. When would you like to start learning 21st Century JavaScript?
• 02-17-2014, 08:24 PM
glenngv
I totally agree that it is recommended to specify the radix when using parseInt to avoid confusion. But when using it to convert css dimensions, the assumed radix will always be 10.

Based from MDN:
Quote:

If radix is undefined or 0 (or absent), JavaScript assumes the following:

1. If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed.
2. If the input string begins with "0", radix is eight (octal) or 10 (decimal). Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet. For this reason always specify a radix when using parseInt.
3. If the input string begins with any other value, the radix is 10 (decimal).

And also using parseInt to convert css dimensions is not an unintended purpose of parseInt.

Again, from MDN:
Quote:

If parseInt encounters a character that is not a numeral in the specified radix, it ignores it and all succeeding characters and returns the integer value parsed up to that point.
• 02-17-2014, 09:20 PM
felgall
Quote:

Originally Posted by glenngv
And also using parseInt to convert css dimensions is not an unintended purpose of parseInt.

Again, from MDN:

The text you quote there doesn't say that one of the purposes of parseInt is for processing css dimensions.

It merely describes what happens if the function fins a characte r that it can't convert to a number

eg. parseInt('fex',16) is 254 with the x ignored whereas parseInt('fex'),35) is 18898 and the x isn't ignored - simply because x is not a valid base 16 number whereas it is a valid base 35 number.

Anyway, why quote a secondary source such as MDN (which contains known errors) rather than the primary source.

Quote:

Originally Posted by http://www.ecma-international.org/ecma-262/5.1/#sec-15.1.2.2

The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. Leading white space in string is ignored. If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, the number may also optionally begin with the character pairs 0x or 0X.

When the parseInt function is called, the following steps are taken:

Let inputString be ToString(string).
Let S be a newly created substring of inputString consisting of the first character that is not a StrWhiteSpaceChar and all characters following that character. (In other words, remove leading white space.) If inputString does not contain any such characters, let S be the empty string.
Let sign be 1.
If S is not empty and the first character of S is a minus sign -, let sign be −1.
If S is not empty and the first character of S is a plus sign + or a minus sign -, then remove the first character from S.
Let stripPrefix be true.
If R ≠ 0, then
If R < 2 or R > 36, then return NaN.
If R ≠ 16, let stripPrefix be false.
Else, R = 0
Let R = 10.
If stripPrefix is true, then
If the length of S is at least 2 and the first two characters of S are either “0x” or “0X”, then remove the first two characters from S and let R = 16.
If S contains any character that is not a radix-R digit, then let Z be the substring of S consisting of all characters before the first such character; otherwise, let Z be S.
If Z is empty, return NaN.
Let mathInt be the mathematical integer value that is represented by Z in radix-R notation, using the letters A-Z and a-z for digits with values 10 through 35. (However, if R is 10 and Z contains more than 20 significant digits, every significant digit after the 20th may be replaced by a 0 digit, at the option of the implementation; and if R is not 2, 4, 8, 10, 16, or 32, then mathInt may be an implementation-dependent approximation to the mathematical integer value that is represented by Z in radix-R notation.)
Let number be the Number value for mathInt.
Return sign × number.
NOTEparseInt may interpret only a leading portion of 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.

Lots there about converting between number bases and truncating without warning if it finds a character that it can't convert but no mention of CSS. Also, that's a lot of unnecessary checking just to chop the number out of CSS.
• 02-18-2014, 09:00 AM
glenngv
I was not saying that MDN specifically says parseInt is for processing css dimensions. Of course not! What I was pointing out was the way it behaves when it encounters a character that cannot be converted to numeric applies to when parseInt'ing css dimensions and using it for css dimensions is not a misuse of the function.

BTW, the primary source that you quoted essentially says the same as MDN does.
Quote:

If radix is undefined or 0, it is assumed to be 10 except when the number begins with the character pairs 0x or 0X, in which case a radix of 16 is assumed. If radix is 16, the number may also optionally begin with the character pairs 0x or 0X.
...
NOTE parseInt may interpret only a leading portion of 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.