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

Turning spelled out answer into a number

Hi! What if I ask about user's age and they spell out their answer, eg. "seventeen"? How do I turn it into an integer?

1 Answer

Tomas Schaffer
Tomas Schaffer
11,606 Points

You can't cast it to number. But the best way how to avoid this problem is to set input value to be number then user may not send you age in string thats all.

<input type = "number"/> even you can put to placeholder default value and user can see what kind of value belongs there

Tomas Schaffer
Tomas Schaffer
11,606 Points

And one more option if you like to you can check in JavaScript typeOf returned value, and set conditional statment, if its tupe of number then you can store it or use it else ask user to put the right value again.

Dawid Gorus
Dawid Gorus
1,808 Points

There is no such thing in development 'You can't ..' You can do it, but there is no build in solution in JS. You have to write your own solution. That will parse 'seventeen' to 17. Search the internet there are lot of examples how to do this properly

Tomas Schaffer
Tomas Schaffer
11,606 Points

Of corse you can do whatever as your own solution, i wrote i my opinion the easiest way how i would do it. If there is a case you need to parse string to number you need to create your own solution. The question was how to avoid this problem and gived a easy example. Thats all. If you need own solution of corse its also poisble. And i agree i used maybe incorect word “cant“.