Howdy, Stranger!

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

Turn a string into a number?

I am trying to write a passage where a person puts in their age with a prompt, then the passage checks if their age is above or below 18, and sends back a specific response. So far I've been getting nothing but error messages. Here's what I've got:

(set: $age to (prompt: "How old are you?"))

Oh, so you're $age?

(if: $age < 18)[You're too young.]
(elseif: $age > 18)[You're old enough.]


But it keeps giving me a response like "I can only do > with numbers, not the string "15""
Do I need to somehow convert the prompt response string into a number? I've had success before doing operations like (if: $num1 > $num2)[blah blah]. That seemed to work fine.

What can I do?

Comments

  • You can use
    (num:$age)
    
    to convert it to a number. I regrettably didn't include it in the documentation, though - once the new documentation I'm working on goes live, these omissions should be all gone.
  • Thanks! I ended up writing the code like this:
    (set: $age to (prompt: "How old are you?"))

    Oh, so you're $age?

    (if: (num: $age) < 18)[You're too young.]
    (else:)[You're old enough]

    And it works great! Thanks for the information!
  • Thanks! I ended up writing the code like this:
    (set: $age to (prompt: "How old are you?"))
    Oh, so you're $age?
    (if: (num: $age) < 18)[You're too young.]
    (else:)[You're old enough]
    And it works great! Thanks for the information!
    Two things about your example:

    1. Check the value the reader supplied.
    Never assume that the reader will actually enter a value when you ask them to or that the value they entered is a valid value.

    2. If you are planning to use the $age variable as a number more than once in your story then you should convert it to a number.
    (set: $age to (prompt: "How old are you?"))
    
    (if: $age is "" or isNaN($age))[(set: $age to 18)]
    (else:)[(set: $age to (num: $age))]
    
    Oh, so you're $age?
    
    (if: $age < 18)[You're too young.]
    (else:)[You're old enough]
    
Sign In or Register to comment.