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

Taylor Fry
Taylor Fry
1,024 Points

parseInt vs parseFloat

Why would you ever use parseInt? I tested it out and you can pass a whole integer to parseFloat and it will display it. Even if you pass it 3.00 it will still just display 3. Why not just always use parseFloat?

2 Answers

Look at this situation:

Note: I'm pretending I'm in the JavaScript console

> parseFloat("3.14");
3.14
> parseInt("3.14");
3
> parseFloat(3.14);
3.14
> parseInt(3.14);
3

As you see, they return different values. I usually use parseInt, actually, so I'm sure I am retrieving integer values. Sometimes, though, you would use parseFloat when you are dealing with floats.

I hope this helps. ~Alex

If this answered your question, don't forget to mark it as a Best Answer! Thank you!

Nourez Rawji
Nourez Rawji
3,303 Points

By using parseInt, you guarantee that your program is type safe. For example, in the video, the user is asked for a total number of badges that they've earned. If you used parseFloat, the user could enter 3.14 for example and have the program accept it. You'd end up in a scenario where a float doesn't make sense, you can't have .14 of a badge, or a three and a half children. When designing a program, you have to think about whether or not having decimals makes sense and use the appropriate number type.