How do I find the length of a number?

Discussion of Common Lisp

How do I find the length of a number?

Postby joeish80829 » Wed May 28, 2014 2:08 am

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
joeish80829
 
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

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

Postby Goheeca » Wed May 28, 2014 2:33 am

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)))
cl-2dsyntax is my attempt to create a Python-like reader. My mirror of CLHS (and the dark themed version).
User avatar
Goheeca
 
Posts: 218
Joined: Thu May 10, 2012 12:54 pm

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

Postby joeish80829 » Wed May 28, 2014 6:51 am

Thanks a lot! That is just what I was looking for. I really do appreciate all these great answers you have given me.
joeish80829
 
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

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

Postby marcoxa » Fri May 30, 2014 5:51 am

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.
Marco Antoniotti
marcoxa
 
Posts: 69
Joined: Thu Aug 14, 2008 6:31 pm


Return to Common Lisp

Who is online

Users browsing this forum: Google [Bot] and 3 guests