www.webdeveloper.com
Results 1 to 5 of 5

Thread: parseInt unexpected behavior

Hybrid View

  1. #1
    Join Date
    Oct 2013
    Posts
    3

    parseInt unexpected behavior

    I am very new to Javascript so please bear with me. I would like to do something simple like pass a variable, have the variable rounded off and then printed. Here' the code I am trying:
    Code:
    var x = prompt("Enter a number to round", 1);
    x = x + 0.5;
    					
    document.write("<p>" + x + "</p>");
    x = parseInt(x);
    document.write("<p>" + x + "</p>");
    I expect this should output 1.5 and 2, but this is the output I get:

    1.50.5

    1

    Any insight would be appreciated.

  2. #2
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,443
    The prompt() function returns a string.
    You then add a number to a string which makes the number think it is a string.
    Hence the 1.50.5 results

    Consider this modification and post back it it doesn't make sense to you...
    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    
    <title> Untitled </title>
    <script type="text/javascript">
    var s = prompt("Enter a number to round", 1.2);
    n = s + 0.5;  document.write("<p>" + n + "</p>");
    
    x = Number(s) + 0.5;  document.write("<p>" + x + "</p>");
    y = parseInt(s);      document.write("<p>" + y + "</p>");
    z = x.toFixed(1);     document.write("<p>" + z + "<br>"+x.toFixed(2)+"</p>");
    </script>
    
    </head>
    <body>
    
    </body>
    </html>
    Last edited by JMRKER; 10-05-2013 at 10:08 PM.

  3. #3
    Join Date
    Oct 2013
    Posts
    3
    Thanks, yes this makes sense. My reading on Javascript claims that the interpreter can "figure out" what the data type of a variable should be. I guess it's not perfect especially since the addition and concatentate operator is the same. The interesting thing is that it does handle other operators. So if I multiply x by something, the result is as I would expect. And if a decimal number is input it can get parsed just fine.

  4. #4
    Join Date
    Oct 2013
    Posts
    3
    So this will work too:
    Code:
    x = parseFloat(x);

  5. #5
    Join Date
    Dec 2005
    Location
    FL
    Posts
    7,443
    Quote Originally Posted by ivanandzorro View Post
    So this will work too:
    Code:
    x = parseFloat(x);
    Yes, so long as x is a valid string.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles