Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format money with cl-format (clojure implementation of common lisp format function)

I'm trying to use cl-format to format money. I want (f 12345.555) ;=> "12,345.56". I get the decimals with the format string "~$" and I get the comma separators with "~:D". How do I combine them?

like image 244
madstap Avatar asked Dec 09 '25 04:12

madstap


1 Answers

With Common Lisp, I would recommand using cl-l10n which supports locales and defines ~N. Alternatively, you could roll your own:

(defun money (stream number colonp atsignp &optional (decimal-places 2))
  (multiple-value-bind (integral decimal) (truncate number)
    (format stream
            (concatenate 'string
                         "~"
                         (and colonp ":")
                         (and atsignp "@")
                         "D"
                         "~0,vf")
            integral
            decimal-places
            (abs decimal))))

(setf *read-default-float-format* 'double-float)

(format nil "~2:@/money/" 123456789.123456789)
=> "+123,456,789.12"

Now, for Clojure, it seems that ~/ is not yet supported by cl-format, so you can't directly replicate the above code. It is probably quicker to use a Java libray (see e.g. this question or this other one).

like image 84
coredump Avatar answered Dec 11 '25 13:12

coredump



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!