From: M. Maher Hakim
Subject: string to num
Date: 
Message-ID: <Qe_t2KS00iQQ88lkl0@andrew.cmu.edu>
Is there an easy way to convert a string of digits into a number and
vice versa.  In other words, I would like to be able to do:

(+ (string-to-num "123") (string-to-num "12.5")) ==> 135.5
(concatenate 'string (num-to-string 123) (num-to-string 12)) ==> "12312"

Thanks

Maher Hakim

From: Barry Margolin
Subject: Re: string to num
Date: 
Message-ID: <10g9ruINNs1o@early-bird.think.com>
In article <··················@andrew.cmu.edu> ·····@andrew.cmu.edu (M. Maher Hakim) writes:
>
>Is there an easy way to convert a string of digits into a number and
>vice versa.  In other words, I would like to be able to do:
>
>(+ (string-to-num "123") (string-to-num "12.5")) ==> 135.5
>(concatenate 'string (num-to-string 123) (num-to-string 12)) ==> "12312"

For integers there's PARSE-INTEGER, but there's nothing else specific to
numbers.  You can use READ-FROM-STRING, and then check that it's a number,
e.g.

(defun string-to-num (string)
  (multiple-value-bind (value end)
      (read-from-string string)
    (if (and (numberp value)
	     (>= end (length string))) ; check for left over characters
	value
	(error "~S is not the representation of a number." string))))
-- 
Barry Margolin
System Manager, Thinking Machines Corp.

······@think.com          {uunet,harvard}!think!barmar
From: Jaime Cisneros
Subject: Re: string to num
Date: 
Message-ID: <1992Jun4.233834.19697@cs.ucf.edu>
One function that I found in "Common Lisp" by Guy L. Steele Jr., says that you
can convert a string to a integer by writing the following function:

  (defun convert-string-to-integer (str &optional (radix 10))
    ;; Given an digit string and optional radix, return an integer.
    (do ((j 0 (+ j 1))
	(n 0 (+ (* n radix)
                (or (digit-char-p (char str j) radix)
	            (error "Bad radix-~D digit: ~C"
	                   radix
                           (char str j))))))
	((= j (length str)) n)))

  I have tried this function, and it seems to work.  Now, if you want
a function to convert from integer to string, try the following:

   (format nil "~s" your-number)

  This will make the number a string.

  I hope this helps,

  Jaime Cisneros
  UCF AI lab
From: Bob Riemenschneider
Subject: Re: string to num
Date: 
Message-ID: <RAR.92Jun2130841@birch.csl.sri.com>
In article <··················@andrew.cmu.edu> ·····@andrew.cmu.edu (M. Maher Hakim) writes:

   Is there an easy way to convert a string of digits into a number and
   vice versa. ...

Use READ-FROM-STRING (or PARSE-INTEGER if you're only dealing with
integers) and FORMAT (or PRIN1-TO-STRING if you don't like FORMAT).
Rewriting the examples, I get

   (+ (read-from-string "123") (read-from-string "12.5")) ==> 135.5
   (concatenate 'string (format nil "~D" 123) (format nil "~D" 12)) ==> "12312"

Shouldn't this be in the FAQs?  (I couldn't find it there.)

								-- rar