Is it possible to do math with the textinput macro

0 votes
asked Aug 24 by gavinjon (140 points)
Is it possible to do math with the textinput macro?  Because as far as I can tell, by default its datatype is always a string.  So am I missing something (like another input macro or some kind of trick) or is it possible to change what type of input textinput accepts / uses?

 

Basically what I want is to be able to use the basic mathematical operators (primarily multiplication and addition) with the input users provide, and I'm having trouble with getting that to work.  If someone could help, that would be great.  Just tell me what you need in order for you to help me.

1 Answer

+1 vote
answered Aug 24 by Chapel (33,020 points)

Yes. For Harlowe, use the (num:) macro to turn a string into a number. For SugarCube and the Twine 1 formats, use the parseInt() function

For future reference, you ought to mention or tag the story format and version you're using. As you can see above, answers and advice are very different based on that information. 

commented Aug 24 by Akjosch (3,950 points)

... and if you also want other values besides integers, use Number($val)

commented Aug 24 by TheMadExile (20,310 points)

I'd recommend the use of Number(), period.  Unless you absolutely need to allow junk characters along with the numerals you're attempting to convert or, specifically to parseInt(), need to convert from a non-decimal base, there is very little reason to prefer either parseInt() or parseFloat() over Number().

Beyond that, parseInt() has some gotchas which can bite you.

  1. In some very ancient browsers, the default base is not 10.  The traditional remedy for that bit of inanity is to always specify the base of the incoming numerals (usually base 10).  e.g. parseInt('22', 10).
  2. In all older browsers, it will treat a leading 0 as signifying that the numerals are base 8 (octal). e.g. parseInt('010') would yield 8, rather than 10.

In summary: Unless you know for a fact that you'll need the unique features of parseInt()/parseFloat(), it's best to simply use Number().

Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...