How do I find the length of a number?

Discussion of Common Lisp
Post Reply
joeish80829
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

How do I find the length of a number?

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

Goheeca
Posts: 271
Joined: Thu May 10, 2012 12:54 pm
Contact:

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

Post by 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). Temporary mirrors of aferomentioned: CLHS and a dark version.

joeish80829
Posts: 153
Joined: Tue Sep 03, 2013 5:32 am

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

Post by 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.

marcoxa
Posts: 85
Joined: Thu Aug 14, 2008 6:31 pm

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

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

Post Reply