2.6 Converting a string to a number

We now learned how to parse strings and retrieve components from them. But what if these components are numbers? Well, there is a way in 4tH to convert a string to a number, but like every number-conversion routine it has to act on invalid strings. That is, strings that cannot be converted to a valid number.

4tH uses an internal error-value, called '(ERROR)'. The constant '(ERROR)' is a strange number. You can't negate it, you can't subtract any number from it and you can't print it. If 4tHs number-conversion word 'NUMBER' can't convert a string it returns that constant. Let's take a look at this program:

     ." Enter a number: "               \ write prompt
     refill drop                   \ enter string
     bl word                       \ parse string
     number dup                    \ convert to a number
     (error) =                     \ test for valid number
     if                            \ if not valid
          ." You didn't enter a valid number!" drop cr
     else                          \ print if valid
          ." The number was: " . cr
     then

You first enter a string, then it parsed and 'WORD' returns the address where that string is stored. 'NUMBER' tries to convert it. If 'NUMBER' returns '(ERROR)' if wasn't a valid string. Otherwise, the number is right on the stack, waiting to be printed. That wasn't so hard, was it?