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 trialja5on
10,338 Pointshow to parseInt and parseFloat on one number?
This is from the teaching video at 3:57 minutes in...
Just to check that my code is right?
I have a number 202.99
I want to use parseInt and parseFloat
let number = (parseInt, parseFloat("202.99"));
// Output below
number = 202.99
typeof number = "number"
I sure that the parseInt worked to convert to a number, I think parseFloat works to include .99 is my code ok?
2 Answers
jb30
44,807 PointsYour code works, but you can simplify your code to let number = parseFloat("202.99");
.
Both parseInt()
and parseFloat()
can convert strings to numbers. To convert "202.99" to an integer, you could use number = parseInt("202.99");
, and the value for number
would be 202
. To convert "202.99" to a float, you could use number = parseFloat("202.99")
, and the value for number
would be 202.99
.
In the code let number = (parseInt, parseFloat("202.99"));
, JavaScript first evaluates the first expression in the parentheses, parseInt
, which has no parentheses, so it refers to the function parseInt()
, and is not printing anything or changing your string. JavaScript next evaluates parseFloat("202.99")
, which evaluates to the number 202.99
, and since it's the last item in the parentheses, its value is assigned to number
.
If you wanted to chain function calls, you could do let number = parseFloat(parseInt("202.99"));
, which first evaluates the inner expression parseInt("202.99")
, which is 202
. JavaScript then evaluates the outer expression with the result of that calculation, and so evaluates parseFloat(202)
, which is 202
, and sets that as the value for number
. You could instead do let number = parseInt(parseFloat("202.99"))
, which simplifies to let number = parseInt(202.99)
, which simplifies to let number = 202;
, which is the same result, the result of let number = parseInt("202.99");
. If you convert a string using the function parseInt()
, you lose everything after the decimal point.
ja5on
10,338 PointsThank you jb30!! I had just progressed onto a challenge and seen this exact thing! I discovered that parseFloat works the same way as parseInt regarding conversion of strings into numbers, something I must have missed...
Thanks for your awesome explanation.
Happy coding..