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 Numbers Working with Numbers Convert Strings to Numbers

Victor Stanciu
seal-mask
.a{fill-rule:evenodd;}techdegree
Victor Stanciu
Full Stack JavaScript Techdegree Student 11,196 Points

Why is "typeof +pi" number, but "typeof(+pi).toFixed(2)" is string?

Hi!

I tried eliminating the possibility of a false return in case the user inserts, for example, 3.14159. For this, I converted the string pi to number using +pi, and then kept only the first two decimals, using (+pi).toFixed(2).

The problem appears when comparing (+pi).toFixed(2) === 3.14. Apparently (+pi).toFixed(2) is a string, and not a number. Why is that? My code is posted below.

const pi = prompt("What is pi?");
// this shows clearly the variable types.
console.log(typeof pi, typeof +pi, (+pi).toFixed(2), typeof (+pi).toFixed(2));
console.log((+pi).toFixed(2) === 3.14);

Thanks so much for your help!

1 Answer

Steven Parker
Steven Parker
231,248 Points

As you discovered, toFixed() returns a string by design, since it is generally used in formatting output.

There are four easy ways around this to accommodate what you're doing:

console.log((+pi).toFixed(2) == 3.14);          // use a coercable ("normal") comparison
console.log(+(+pi).toFixed(2) === 3.14);        // convert the result back into a number
console.log((+pi).toFixed(2) === "3.14");       // compare with a string
console.log(Math.round(+pi*100)/100 === 3.14);  // use an entirely numeric alternative