Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 13 of 13
  1. #1
    New to the CF scene
    Join Date
    Feb 2014
    Location
    London, UK
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Smile 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


    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.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    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.
    Instead of parseInt() use Number()
    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.
    Instead of document.write use innerHTML.
    Last edited by felgall; 02-13-2014 at 09:33 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • Users who have thanked felgall for this post:

    Olive85 (02-13-2014)

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,400
    Thanks
    11
    Thanked 595 Times in 575 Posts
    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...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #4
    New to the CF scene
    Join Date
    Feb 2014
    Location
    London, UK
    Posts
    6
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Quote Originally Posted by felgall View Post
    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.
    Instead of parseInt() use Number()
    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.
    Instead of document.write use innerHTML.
    Yeah, I am a uni student, and I have got JavaScript module for 9 weeks

  • #5
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    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.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #6
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,074
    Thanks
    0
    Thanked 256 Times in 252 Posts
    Quote Originally Posted by felgall View Post
    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);
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by glenngv View Post
    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
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,400
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by felgall View Post
    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...
    Last edited by rnd me; 02-15-2014 at 08:00 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #9
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    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.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #10
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by rnd me View Post
    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 View Post
    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?
    Last edited by felgall; 02-15-2014 at 08:30 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #11
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,074
    Thanks
    0
    Thanked 256 Times in 252 Posts
    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:
    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:
    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.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________

  • #12
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by glenngv View Post
    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
    15.1.2.2 parseInt (string , radix)

    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 R = ToInt32(radix).
    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.
    Last edited by felgall; 02-17-2014 at 09:26 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #13
    Supreme Master coder! glenngv's Avatar
    Join Date
    Jun 2002
    Location
    Philippines
    Posts
    11,074
    Thanks
    0
    Thanked 256 Times in 252 Posts
    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.
    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.
    Last edited by glenngv; 02-18-2014 at 09:04 AM.
    Glenn
    ____________________________________

    My Blog
    Tower of Hanoi Android app (FREE!)
    Tower of Hanoi Leaderboard
    Samegame Facebook App
    vBulletin Plugins
    ____________________________________


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •