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

Can you prompt for a number, have someone write 'fifty-two', and have JavaScript convert that to a number?

What I mean is, say you have this situation:

var HTMLBadges = prompt("How many badges do you have?");

And the person responds with "fifty-two" in text. Can I use JavaScript to either 1. force them to use only a number or 2. convert the text to 52, like parsetInt does for changing a string of "52" to the number 52?

3 Answers

James Barnett
James Barnett
39,199 Points

It's not very simple to do but you can do it.

There's an NPM module to do just that

https://github.com/raitucarp/wtn/blob/master/index.js

You could certainly force them to type a number by doing a loop and checking if number is an int or not..

To convert the fifty-two to 52.. you would need an array where fifty-two maps to 52.. but it can get ugly what if user types fiftytwo or fifty two.. etc.. you have 3 variation for each number..

Greg Kitchin
Greg Kitchin
31,522 Points

Funnily enough just covered this in my uni work (I'll paraphrase it here, the notes I've been given are pretty bad). What you're asking about is validation, basically you are trying to make sure a valid answer is given. So as the previous poster mentions, it's possible to check the variable to see if it's a number or text, and if the valid response is not given, try again and progress until the proper value type is given. As an example in pseudo-code,

Make a variable VALUE of type INT. Open a PROMPT box, ask in it "Please enter a number" and make the result the value of INT If INT is not a number, then open the PROMPT box again, ask in it "Please enter a number" and make the result the value of INT Else, Go to next part of your code.

Also, it would be possible to convert a text value to an int, essentially check if it equates to 'fifty-two'. and if so, make it an int value of '52'. But you'd have to do that for every other number possible and that's just not practical.