Page 1 of 1

How do I find the length of a number?

Posted: Wed May 28, 2014 2:08 am
by joeish80829
is there anyway to find the length of a number e.g.

Code: Select all

 (length 1234567890) 
would equal 10, or:

Code: Select all

(length 5487)
would equal 4

Re: How do I find the length of a number?

Posted: Wed May 28, 2014 2:33 am
by Goheeca
Mathematical way:

Code: Select all

(defun number-length (num)
  (if (zerop num)
      1
      (1+ (floor (log num 10)))))
or text-representation-way:

Code: Select all

(defun number-length (num)
  (length (format nil "~s" num)))

Re: How do I find the length of a number?

Posted: Wed May 28, 2014 6:51 am
by joeish80829
Thanks a lot! That is just what I was looking for. I really do appreciate all these great answers you have given me.

Re: How do I find the length of a number?

Posted: Fri May 30, 2014 5:51 am
by marcoxa
Define "length of a number". For INTEGERs it is one thing, for floating point numbers not so easy.

In any case, you have INTEGER-LENGTH in ANSI, which may or may not be of use.