Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.