Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Converting variables? (string to numeric)

Hi all -

  I'm attempting to gather numeric user input, which I then need to do math to.  Nothing complicated, just adding and storing in an overall variable - no other validation or anything.

  Is there a way I can either 1) use the prompt function to store a number as numeric rather than as a string? or 2) convert a string to a numeric format?

Thanks in advance!

-Eric

Comments

  • You can parse a numeric string into a number via the parseInt() function:

    <<set $number = parseInt($numericString, 10)>>

    /% You can set the return value of prompt() to a $variable and then parse that: %/
    <<set
    $userInput = prompt();
    $number = parseInt($userInput, 10);
    >>

    /% Or, you can simply feed the return value of prompt() directly into parseInt(): %/
    <<set $number = parseInt(prompt(), 10)>>
    Either way, I'd check the return value of parseInt() with the isNaN() function, since that's what you'll have if the player decides to enter a non-numeric string for whatever reason.  For example:

    <<if isNaN($number)>>
    /% Not-a-Number! Yell at the player and make them do it again. %/
    <<else>>
    /% Seems legit, send the player on %/
    <<endif>>
    You could also do range validation at that point, if that's something you need/want to do.
  • That worked great for me.  Thanks for the thorough reply!
  • Sure.  I should also have mentioned the parseFloat() function, in case you ever needed to parse a real.
Sign In or Register to comment.