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

Nate Jonah
Nate Jonah
20,981 Points

Confused about parseFloat()

I thought I'd try out the parseFloat() command but it only kind of works in my own example but only if I log just the converted strings to the console but not when I combine them with a string.

When I wrote this (my values were 4.50 + 5.50 + 2.50):

var orangesPrice = prompt('How much do oranges cost?');
var bananasPrice = prompt('How much do bananas cost?');
var applesPrice = prompt('How much do oranges cost?');

console.log(parseFloat(orangesPrice) + parseFloat(bananasPrice) + parseFloat(applesPrice));

The console returned 12.5

But when I wrote this:

var orangesPrice = prompt('How much do oranges cost?');
var bananasPrice = prompt('How much do bananas cost?');
var applesPrice = prompt('How much do oranges cost?');

console.log('Wow! Fruit costs ' + parseFloat(orangesPrice) + parseFloat(bananasPrice) + parseFloat(applesPrice) + '? That is way too expensive!');

The console returned: "Wow! Fruit costs 4.55.52.5? That is way too expensive!"

The values are still strings right? I don't understand why it's doing that. I didn't have this problem with parseInt()

1 Answer

Hello Nate,

What is happening here is the first example is converting the numbers into a string due to concatenation. It is taking all the entered values and adding them as string values as is, rather than adding them first.

To avoid this problem you can do change the order of operation by adding parenthesis around the parseFloats, this way they get added together before logging the entire string.

Like this. jsFiddle Example

console.log('Wow! Fruit costs ' + (parseFloat(orangesPrice) + parseFloat(bananasPrice) + parseFloat(applesPrice)) + '? That is way too expensive!');

I hope this helps.

Beat me to it! :) Removed my very similar reply.

Nate Jonah
Nate Jonah
20,981 Points

Ahh I get it now. Thanks so much for your help, Chyno!