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
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
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
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