help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Elisp version of CL: (format t "~:d" NUM)


From: Jean Louis
Subject: Elisp version of CL: (format t "~:d" NUM)
Date: Fri, 21 May 2021 22:02:40 +0300

In Common Lisp it is very easy to get readable comma separated digits:

(clisp-macro (format t "~:d" 123456890)) ⇒ "123,456,890"

As from:
http://www.lispworks.com/documentation/HyperSpec/Body/22_cbb.htm

In Emacs Lisp I have made this below, did not tested it much yet. And
I think this function is way too big. Maybe there is some simpler way?

(defun number-comma-char (num)
  "For NUM return readable comma separated digits."
  (let* ((num (cond ((numberp num) (number-to-string num))
                    (t num)))
         (decimal (string-match "\\." num))
         (rest (if decimal (substring num decimal) ""))
         (num (if decimal (substring num 0 decimal) num))
         (count 1)
         (list)
         (chain (seq-map 'identity (reverse num))))
    (while chain
      (let ((char (pop chain)))
        (cond ((and (= (truncate (/ count 3.0)) (/ count 3.0))
                    chain)
               (progn
                 (push char list)
                 (push ?, list)))
              (t (push char list)))
        (setq count (1+ count))))
    (concat (mapconcat 'char-to-string list "") rest)))

(number-comma-char 123456.0) ⇒ "123,456.0"



Jean

Take action in Free Software Foundation campaigns:
https://www.fsf.org/campaigns

Sign an open letter in support of Richard M. Stallman
https://stallmansupport.org/



reply via email to

[Prev in Thread] Current Thread [Next in Thread]