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 Numbers and Strings

Michel van Essen
Michel van Essen
8,077 Points

I'm unsure if I'm jumping the gun but what if you need input that could be both integers or floating numbers?

How about things like weight? or length? and what if the answer to a couple of prompts is an integer while the question asked for floating numbers? For example 3.8 + 1.2?

3 Answers

Hi Michel,

It's up to you, as the program author, to decide how you want to interpret the input - which comes in as a string. Parsing a float to an integer will remove all values beyond the decimal (i.e. truncate). Parsing an integer to a float will have no apparent effect. JavaScript doesn't care if you're adding floats to ints.

If you think there's a chance you might need floats you should use parseFloat, it will function just the same.

Michel van Essen
Michel van Essen
8,077 Points

Got it, so I'll basically use parseFloat more than parseInt which lead me to the following question, why even bother using parseInt?

By the way Geoff, that's one nice epic beard you got there!

Gina BΓ©gin
Gina BΓ©gin
Courses Plus Student 8,613 Points

Michel van Essen, did you ever figure out the reason for using parseInt? I noticed it wasn't answered, but I'd like to know as well. Geoff Parsons or Robert Richey β€” any insight?

Clara Roldan
Clara Roldan
3,074 Points

You might not want a number with decimals returned. For example, imagine asking a user "Hoy many pixels should the box have?". The user might not know pixels can't have decimals and type 10.5px, so you parseInt() the value and discard the decimal. Silly example, of course you could also check the input and throw an error if it's not an integer...