/    Sign up×
Community /Pin to ProfileBookmark

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>”);

[/CODE]

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.

to post a comment
JavaScript

4 Comments(s)

Copy linkTweet thisAlerts:
@JMRKEROct 06.2013 — 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...
<i>
</i>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="UTF-8" /&gt;

&lt;title&gt; Untitled &lt;/title&gt;
&lt;script type="text/javascript"&gt;
var s = prompt("Enter a number to round", 1.2);
n = s + 0.5; document.write("&lt;p&gt;" + n + "&lt;/p&gt;");

x = Number(s) + 0.5; document.write("&lt;p&gt;" + x + "&lt;/p&gt;");
y = parseInt(s); document.write("&lt;p&gt;" + y + "&lt;/p&gt;");
z = x.toFixed(1); document.write("&lt;p&gt;" + z + "&lt;br&gt;"+x.toFixed(2)+"&lt;/p&gt;");
&lt;/script&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;/body&gt;
&lt;/html&gt;
Copy linkTweet thisAlerts:
@ivanandzorroauthorOct 06.2013 — 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.
Copy linkTweet thisAlerts:
@ivanandzorroauthorOct 06.2013 — So this will work too:
[CODE]
x = parseFloat(x);
[/CODE]
Copy linkTweet thisAlerts:
@JMRKEROct 06.2013 — So this will work too:
[CODE]
x = parseFloat(x);
[/CODE]
[/QUOTE]


Yes, so long as x is a valid string.
×

Success!

Help @ivanandzorro spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...