Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Basics (Retired) Working With Numbers The Math Object

Rocket Alpaca
Rocket Alpaca
7,318 Points

parseInt(.5) vs parseInt(".5")

Why is it that only the string runs into an error of NAN?

2 Answers

It's kind of a two step answer.

  1. parseInt() expects a string for the parameter. When you run parseInt(.5), it automatically converts the non-string .5 into the string "0.5". (Note the leading zero).

  2. When parseInt runs, it expects the first character of the string to be numeric. So "55 cows" will parse to 55, but "cows 55" will return NaN.

Therefore, since ".5" starts with a decimal point instead of a number, it returns NaN. Do it again as parseInt("0.5") and you'll get the same result as parseInt(.5).

Rocket Alpaca
Rocket Alpaca
7,318 Points

That makes sense, thanks!

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

Hey Nicholas . I run the code as you mentioned :


1 is giving "NaN" as output but 2 is giving 0 as output.

NaN means 'Not a Number'. A string is not a number. .5 without quotes is a number. .5 with quotes is a string.