28

I tried to find a lisp function to convert between numbers and strings and after a little googling I fond a function with the same name. when I entered (itoa 1) SLIME printed:

Undefined function ITOA called with arguments (1) .

How can I do the conversion?

Rainer Joswig
  • 136,269
  • 10
  • 221
  • 346
elyashiv
  • 3,623
  • 2
  • 29
  • 52

3 Answers3

60

From number to string:

(write-to-string 5)
"5"

you may transform a string to any numerical notation:

(write-to-string 341 :base 10)
"341"

From string to number:

(parse-integer "5")
5

with some trash

(parse-integer " 5 something not a number" :junk-allowed t)
5

Or use this:

(read-from-string "23 absd")
23
edem
  • 3,222
  • 3
  • 19
  • 45
  • 2
    Do not use `read-from-string` on externally provided strings, or at least bind `*read-eval*` to false when you do. Also of note for general number-parsing is the library `parse-number`. – Svante May 01 '13 at 21:26
  • 1
    Seems that `(write-to-string)` is depracated. Use `(number-to-string)` instead, see https://www.gnu.org/software/emacs/manual/html_node/elisp/String-Conversion.html. – Student Apr 22 '20 at 16:27
  • @Student Looks like you assume this to be emacs lisp only. – BitTickler Jul 20 '23 at 16:45
20

A heavyweight solution is to use FORMAT:

[2]> (format nil "~A" 1)
"1"

There is also WRITE-TO-STRING:

[3]> (write-to-string 10)
"10"
Paul Nathan
  • 39,638
  • 28
  • 112
  • 212
  • 2
    Thank you for linking to the CLHS. That helps make this answer more useful than it otherwise would be. – lindes Apr 17 '16 at 16:18
1

FYI: I believe (itoa #) is only a function in AutoLISP - the LISP variant embedded in AutoCAD drafting software. AutoLISP has far fewer functions than Common Lisp and sometimes identical functions with a different name or functions with the same name that operate differently.

That's probably why it didn't work for you. I use AutoLISP regularly and (itoa #) would do exactly what you want there.

J.D. Sandifer
  • 814
  • 9
  • 20